image picker,但是在将其更新为null-safety之后,我将File _image;更改为late File _image;,并且使用Center(child: _buildImage()),显示所选的图像。因此,在更改null-safety之后,我得到了错误LateInitializationError: Field '_image@63124145' has not been initialized.。我无法理解如何初始化我的variable File _image;
// choose the image
late File _image;
Future<void> captureImage(ImageSource imageSource) async {
try {
final picker = ImagePicker();
final pickedFile = await picker.getImage(
source: ImageSource.gallery, maxHeight: 300, maxWidth: 300);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
} catch (e) {
print(e);
}
}
// displaying image
Widget _buildImage() {
// ignore: unnecessary_null_comparison
if (_image != null) {
return Image.file(_image);
} else {
return Text('Choose an image to show', style: TextStyle(fontSize: 18.0));
}
}
...
@override
Widget build(BuildContext context) {
...
final _height = MediaQuery.of(context).size.height;
final _width = MediaQuery.of(context).size.width;
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
...
// choose image
Container(
padding: EdgeInsets.symmetric(
vertical: _height * 0.015,
),
child: FractionallySizedBox(
widthFactor: 1,
child: TextButton(
child: Text(
'Choose File',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
fontFamily: 'Montserrat',
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
onPressed: () =>
captureImage(ImageSource.gallery),
),
),
),
SizedBox(
height: _height * 0.015,
),
// display image
Center(child: _buildImage()),发布于 2021-07-11 09:28:45
不要使用late File _image;,而是使用File? _image;之类的可空文件
以及为塑造形象
// displaying image
Widget _buildImage() {
// ignore: unnecessary_null_comparison
if (_image != null) {
return Image.file(_image!);
} else {
return Text('Choose an image to show', style: TextStyle(fontSize: 18.0));
}
}https://stackoverflow.com/questions/68334744
复制相似问题