I used to Image Picker Plug-in When sending when sending the data to server.
But, There is no problem sending the image to the server, but problems occur when I do not send the image.
I tried some things, but I failed. I want to know how I can send it without data in the image picker.
// image picker
final pickedFile = await ImagePicker.platform
.pickImage(source: ImageSource.gallery, imageQuality: 50);
img = pickedFile.path;
var data = {
...
, 'img' : img
}
....
// formdata
FormData formData = FormData.fromMap({
...
**case1** : 'img': await MultipartFile.fromFile(data['img']) // _TypeError (type 'Null' is not a subtype of type 'String')
**case2** : 'img': await MultipartFile.fromFile(data['img'].toString())
// FileSystemException (FileSystemException: Cannot retrieve length of file, path = 'null' (OS Error: No such file or directory, errno = 2))
**case3** : 'img': await MultipartFile?.fromFile(data['img']!) // _CastError (Null check operator used on a null value)
});
CodePudding user response:
you can use like this :
var data = {
'img' : img
};
// formdata
FormData formData = FormData.fromMap({
'img': data['img'] == null ? null : await MultipartFile.fromFile(data['img'])
});
it will send image data img parameter as null when image path is null.
CodePudding user response:
In Dart you can use ??
to specify a value when a variable is null, in your example you can write:
// image picker
final pickedFile = await ImagePicker.platform
.pickImage(source: ImageSource.gallery, imageQuality: 50);
img = pickedFile.path;
var data = {
...
, 'img' : img ?? 'the data you want to send if img is null'
}
// formdata
FormData formData = FormData.fromMap({
'img': await MultipartFile.fromFile(data['img'])
});