I have a flutter web application in which I am trying to integrate a photo taking functionality. I tried the file_picker package, but for some reason the application sometimes crashes. It seems to be a device-related memory issue. I tested on Iphone SE and Samsung S21. Here is the code that allows me to collect images:
pickImage(Question question, context) async {
try {
FilePickerResult? result = await FilePicker.platform
.pickFiles(type: FileType.image, allowMultiple: true, allowCompression: true);
if (result != null && result.files.isNotEmpty) {
for (int i = 0; i < result.files.length; i++) {
PlatformFile file = result.files[i];
Uint8List? imageBytes = file.bytes!;
Uint8List? compressedImage = await compressImage(imageBytes);
question.addImage(
'IMG_${DateTime.now().millisecondsSinceEpoch.toString()}');
question.addImageData(compressedImage);
imageBytes = null; compressedImage = null;
}
result = null;
}
} catch(e) {
print('ImagePicker failed : $e');
}
}
Future<Uint8List> compressImage(Uint8List imageBytes) async {
final List<int> compressedBytes = await FlutterImageCompress.compressWithList(
imageBytes,
quality: 10,
);
return Uint8List.fromList(compressedBytes);
}
In the previous code, I try to free the memory by setting my variables to null, but the problem persists, and I don't understand why. Should i use another package ??
Edit I've just tried another package, image_picker, and it's all the same when i use my PWA from my mobile. After a few images picked, no error message, but the app crashes and reload...
final ImagePicker picker = ImagePicker();
Future<void> _pickImage() async {
try {
final XFile? pickedFile =
await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
final imageBytes = await pickedFile.readAsBytes();
final base64Image = base64Encode(imageBytes);
setState(() {
imgList.add(base64Image);
});
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(e.toString()),
),
);
}
}
What am I doing wrong? Thank you in advance for your help.