I’m trying to use the image_picker 1.1.2 package in my project to select images from the gallery, but the image I picked doesn’t show up.
This is the important part of the code:
Widget build(BuildContext context) {
File? image;
Future pick() async {
final ImagePicker picker = ImagePicker();
final picked = await picker.pickImage(source: ImageSource.gallery);
File file = File(picked!.path);
setState(() {
image = file;
});
}
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
foregroundColor: Colors.white,
backgroundColor: const Color.fromRGBO(34, 30, 204, 50),
title: Text('new'.tr()),
),
body: Container(
padding: const EdgeInsets.only(top: 20, right: 10, left: 10),
child: Center(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(width: 20),
image == null
? const Text('No photo')
: Image.file(
image!,
width: 100,
height: 100,
fit: BoxFit.fill,
),
IconButton(onPressed: pick, icon: const Icon(Icons.photo))
],
),
Form(
key: key3,
child: Expanded(
child: ListView(
children: [...
2
Answers
The
image
is declared inside build function, so it is a local variable and is reset in the rebuild. It should be a property of theState
instead.Yes, PurplePolyhedron’s answer is correct.
To explain in more detail, when you call
setState()
in the State class,State.build()
is always called again.So when you click on the IconButton and call the pick method,
the following process happens:
That’s why the image doesn’t appear.
So if it is managed as a State outside the build, it will not be reinitialized after setState.