我正在處理顫振專案并將影像檔案上傳到 mysql 服務器,但在螢屏上我收到此錯誤:
LateInitializationError:欄位“_image@785213298”尚未初始化。
這是我正在使用的代碼:
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");
}
}
并使用按鈕選擇檔案:
onPressed: () {
choice2Image();
},
和
onPressed: () {
choiceImage();
},`
并在容器中顯示選定的影像:
Container(
child: Image.file(
_image,
fit: BoxFit.cover,
),
),
我知道這是后期初始化,它指出我從未初始化過的變數,但它在選擇照片或拍照后獲得了它的值,我做錯了什么?
提前致謝。
uj5u.com熱心網友回復:
代替
遲到的檔案 _image;
放
檔案?_圖片;
Container(
child: _image != null? Image.file(
_image,
fit: BoxFit.cover,
) : const SizedBox(),
),
和 uploadImage() 如果 _image != null
uj5u.com熱心網友回復:
而不是使用后期,您可以使用 null(?) 運算子來處理該影像情況,因為后期函式需要初始化值,因此您可以在檔案選擇中使用 (?)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383455.html
