Reputation: 39
Error: Field '_image' should be initialized because its type 'File' doesn't allow null.
code:
child: _image != null ? null : Image.file(_image,fit: BoxFit.fill,),
Upvotes: 1
Views: 364
Reputation: 2327
Check this code,you need to use setState in image selection function to update the view or show the image
class _MyHomePageState extends State<MyHomePage> {
File? _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null
? Text('No image selected.')
: Image.file(_image!),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
Upvotes: 1
Reputation: 603
You must initialize _image using File _image;
Then inside setState use _image = File(pickedFile.path);
pickedFile is return from ImagePicker. Please send full code for more customized answer
Upvotes: 0