lateinitializationerror字段imageFile尚未初始化



我正在尝试从flutter web项目的图库上传一张图片。然而,当我点击上传按钮时,我会收到一个错误"==========小部件库捕获到异常=====================================LateInitializationError:字段imageFile尚未初始化">是什么原因导致了这个错误?这是我的代码:

final picker = ImagePicker();
late File imageFile;
Future chooseImage(ImageSource source) async {
final pickedFile = await picker.pickImage(source: source);
setState(() {
imageFile = File(pickedFile!.path);
});
}
Container(
child: imageFile != null ?
Container(
height: 200,
width: 200,
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(imageFile),
),
borderRadius: BorderRadius.circular(20)),
padding: const EdgeInsets.all(15.0),
) :
Padding(
padding: const EdgeInsets.all(15.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
defaultPic,
height: 250.0,
width: 300.0,
fit: BoxFit.cover,
),
),
),
),
ElevatedButton(
onPressed: () {
chooseImage(ImageSource.gallery);
},
child: Text('Upload Picture'),
style: ElevatedButton.styleFrom(
primary: Colors.red,
elevation: 3,
shape: new RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
),
)

我创建了一个bool变量来实现这一点:

PickedFile? pickedImage;
late File imageFile;    
bool _load = false;

未来将是这样的:

Future chooseImage(ImageSource source) async {
final pickedFile = await picker.pickImage(source: source);
setState(() {
imageFile = File(pickedFile!.path);
_load = false;
});
}

在容器中使用它:

Container(
child: _load == true ?
Container(
height: 200,
width: 200,
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(imageFile),
),
borderRadius: BorderRadius.circular(20)),
padding: const EdgeInsets.all(15.0),
) :
Padding(
padding: const EdgeInsets.all(15.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
defaultPic,
height: 250.0,
width: 300.0,
fit: BoxFit.cover,
),
),
),
),
ElevatedButton(
onPressed: () {
chooseImage(ImageSource.gallery);
},
child: Text('Upload Picture'),
style: ElevatedButton.styleFrom(
primary: Colors.red,
elevation: 3,
shape: new RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
),
)

您确定imageFile已正确初始化吗?我认为问题在于,当您设置imageFile的值时,您将其设置为null。检查File(pickedFile!.path)我认为这是空的。1最后一件事永远不要使用!运算符,最好使用?。基本上,您需要检查pickedFile.path != null

相关内容

  • 没有找到相关文章

最新更新