I have a problem getting images using imagePicker to work in a listview. When you press one of the containers in the listview you should be able to choose an image from the gallery. But, it’s show same image for the whole list in listview. I think it’s should use index for different the image shown. Any suggestions code examples please!
final ImagePicker picker = ImagePicker();
ListView.builder(
itemCount: chilList!.length,
itemBuilder: (context, i) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blueAccent),
onPressed: () {
myAlert(i);
},
child: Text('Upload Image'),
),
image != null
? Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
//to show image, you type like this.
File(image!.path),
fit: BoxFit.cover,
width:
MediaQuery.of(context).size.width,
height: 300,
),
),
)
: Text(
'',
style: TextStyle(fontSize: 20),
),
})
void myAlert(i) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
title: Text('Please choose media to select'),
content: Container(
height: MediaQuery.of(context).size.height / 6,
child: Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.blueAccent),
//if user click this button, user can upload image from gallery
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.gallery, i);
},
child: Row(
children: [
Icon(Icons.image),
Text('From Gallery'),
],
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.blueAccent),
//if user click this button. user can upload image from camera
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.camera, i);
},
child: Row(
children: [
Icon(Icons.camera),
Text('From Camera'),
],
),
),
],
),
),
);
});
}
Future getImage(ImageSource media, i) async {
var img = await picker.pickImage(source: media);
setState(() {
image = img;
});
}
Every list with different image upload
2
Answers
You should create a list of files and store gallery images on different indices.
For Example :-
If i not wrong, the issue you’re facing comes from using a single image variable for all the items in your ListView. Since image is shared, every item ends up displaying the same image. You need to maintain a separate image for each item in the list. This can be done by creating a list to hold images, where each index corresponds to a specific item in the list.
for example: