I need to upload a picture taken with the device´s camera.
Here you have the code:
XFile? _image;
Future getImagefromcamera() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
setState(() async {
_image = image ;
conFoto = true;
File file = File(image?.path);
_upload(file);
});
}
void _upload(File file) {
if (file == null) return;
setState(() {
});
String base64Image = base64Encode(file.readAsBytesSync());
String fileName = file.path.split("/").last;
http.post(Uri.parse(phpEndPoint), body: {
"image": base64Image,
"name": fileName,
}).then((res) async {
print(res.statusCode);
setState(() {
print("***********SOURCE subido:" fileName);
});
}).catchError((err) {
print(err);
});
}
I am getting an error at line
File file = File(image?.path);
Error: The argument type 'String?' can't be assigned to the parameter type 'String'
CodePudding user response:
The problem here is, the XFile
in your case the image
variable can be null. So if it is null then it's not possible to get a path from it and make a file.
So just need to little null check
. By doing this
File file = File(image?.path? ?? "");
Which says, if the path string
doesn't exist, the use the empty string
.
Or if you are supper confident that image
file will definitely exist, then what you can do is, this
File file = File(image!.path);
In this case, your function will throw
an error if the image file doesn't exist.