i am working with flutter project and uploading a image file to mysql server but on the screen i get this error:
LateInitializationError: Field '_image@785213298' has not been initialized.
and this is the code which i am using:
late File _image;
Future choiceImage() async{
final picker=ImagePicker();
var pickedImage= await picker.getImage(source: ImageSource.gallery);
setState(() {
_image=File(pickedImage!.path);
});
}
Future choice2Image() async{
final picker=ImagePicker();
var pickedImage= await picker.getImage(source: ImageSource.camera);
setState(() {
_image=File(pickedImage!.path);
});
}
Future uploadImage() async{
final uri=Uri.parse("https://www.example.com/driverapp-apis");
var request =http.MultipartRequest('POST',uri);
request.fields['id']=widget.id.toString();
request.fields['licence']=licenseController.text;
request.fields['expiry']=expiryController.text;
request.fields['action']="updateDocs";
var pic =await http.MultipartFile.fromPath("image", _image.path);
request.files.add(pic);
var response=await request.send();
if (response.statusCode==200){
print("image uploaded");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => aadharCardScreen(widget.id),
),
);
}
else{
print("image not uploaded");
}
}
and also selcting file with buttons:
onPressed: () {
choice2Image();
},
and
onPressed: () {
choiceImage();
},`
and also showing the selected image in container:
Container(
child: Image.file(
_image,
fit: BoxFit.cover,
),
),
i know that is late initialization which states that variable i never initialized but it gets its value after choosing photo or taking photos, what i am doing wrong?
thanks in advance.
CodePudding user response:
Instead of
late File _image;
set
File? _image;
Container(
child: _image != null? Image.file(
_image,
fit: BoxFit.cover,
) : const SizedBox(),
),
and uploadImage() if _image != null
CodePudding user response:
rather then using late you can use null(?) operator to handle that image case because late function required to initialize value so you can use (?) in file selection.