I'm trying to add uploading user photos to firebase storage in my app. It is a simple script - I start by getting the photos via image_picker and then I want to upload it to the cloud. Here, however, I encounter an error. If I understand correctly, Flutter Web stores picked photos differently, so they should be converted first to uint8list, but the line that is responsible for this crashes my application. This process works normally on Android. Flutter doctor is also ok.
Here is a piece of code that is responsible for uploading and picking an image:
final pickedFiles = await imgPicker.pickMultiImage();
List<XFile> xfilePickList = pickedFile;
List<File> imagesList = [];
if (xfilePickList.isNotEmpty) {
for (int i = 0; i < xfilePickList.length; i++) {
imagesList.add(File(xfilePickList[i].path));
}
}
for (int i = 0; i < imagesList.length; i++) {
final Reference storageRef = FirebaseStorage.instance
.ref()
.child('images')
.child('$i.jpeg');
final imageBytes = await imagesList[i].readAsBytes(); //here it crashes
await storageRef.putData(
imageBytes,
);
}
And here is the error that shows after running:
Error: Unsupported operation: _Namespace
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 297:3 throw_
dart-sdk/lib/_internal/js_dev_runtime/patch/io_patch.dart 205:5 get _namespace
dart-sdk/lib/io/file_impl.dart 489:31 openSync
dart-sdk/lib/io/file_impl.dart 574:18 readAsBytesSync
packages/fileapp/screens/main/content/upload.dart 1745:45 _uploadFile
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54 runBody
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 127:5 _async
packages/fileapp/screens/main/content/upload.dart 1718:19 [_uploadFile]
packages/notespaceapp/screens/main/content/upload.dart 1715:5 initState
packages/flutter/src/widgets/framework.dart... (and here it repeats rebuild and update framework.dart errors)
For flutter web you can try file_picker
//create an empty list of type "PlatformFile"
List<PlatformFile> imagesList = [];
//Create a button and tap on this button to open window to select files
TextButton(
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowMultiple: true,
allowedExtensions: ['jpeg', 'png', 'webp']); //supported extensions
if (result != null) {
if (result.files.isNotEmpty) {
for (int i = 0; i < result.files.length; i++) {
imagesList.add(result.files[i]);
}
}
}
},
child: Text('select images')),
For upload images on firebase storage
Future<void> uploadImage(List<PlatformFile> imagesList) async {
for (int i = 0; i < imagesList.length; i++) {
await FirebaseStorage.instance
.refFromURL('gs://your_storage_bucket_url') //enter your storage bucket url from google_services.json
.child('images')
.putData(
imagesList[i].bytes!,
SettableMetadata(contentType: 'image/${imagesList[i].extension}'),
);
}
}