I'm using image_picker
in my Flutter app. When I test my app in Flutter web, it says I can't use path
parameter in Flutter web.
However, I need to get the path of the image. How to do it?
I googled this, I asked Google Bard and ChatGPT, but didn't find a solution.
I tried changing to using image_picker_web
without success finding a solution.
Some of my code:
XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image != null) {
if ((await File(image.path).length()) > 1000000) {
return "Oversize";
} else {
TaskSnapshot selectedImage = await …(id, File(image.path));
return await selectedImage.ref.getDownloadURL();
}
}
Yes in Flutter web you can't work with paths so in my case I used file_picker package to pick a file and specified the type of files I needed then I used mime to get the mime type. My upload file looks like this:
uploadFiles() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowMultiple: false,
allowedExtensions: ['jpg', 'pdf', 'doc'],
);
if (result != null && result.files.isNotEmpty) {
final fileBytes = result.files.first.bytes;
final fileName = result.files.first.name;
final mime = lookupMimeType('', headerBytes: fileBytes);
return DocModel(
name: fileName,
mimeType: mime,
fileBytes: fileBytes,
file: File.fromRawPath(fileBytes!),
);
} else {
// User canceled the picker
return DocModel();
}
}
Then my DocModel
looks like this:
class DocModel {
int? id;
String? path;
String? name;
File? file;
String? mimeType;
Uint8List? fileBytes;
DocModel({
this.path,
this.name,
this.file,
this.mimeType,
this.id,
this.fileBytes,
});
}
Then to display the image I used Image.memory(fileBytes from model)
.
Working code can be found here Github.