I am new to flutter. I want to add multiple images as well as single to flutter website which I am creating. I am unable to do that I watched many tutorials but nothing helped me out. that's why I came here. This is the stuff i have done so far...
final picker = ImagePicker();
List<File> images = [];
List<int> imageFiles = [];
void _imgFromGallery() async {
List<XFile>? files = await picker.pickMultiImage(
imageQuality: 50,
);
if (files != null) {
for (var element in files) {
setState(() {
images.add(File(element.path));
});
}
}
}
Here i am adding the images in ListView.Builder
Text(
'Attachments',
style: AppTextStyles.boldBlack,
),
const SizedBox(
height: 10,
),
images.isEmpty
? const SizedBox()
: SizedBox(
height: 90,
child: ListView.builder(
shrinkWrap: true,
itemCount: images.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Image.file(
images[index],
height: 80,
width: 80,
),
GestureDetector(
onTap: () {
setState(() {
images.remove(images[index]);
});
},
child: const Icon(Icons.close),
),
],
);
},
),
),
DottedBorder(
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 25,
horizontal: 10,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: [
Center(
child: GestureDetector(
onTap: () {
_imgFromGallery();
}, //
child: const Text(
'Upload Files',
style: TextStyle(
decoration: TextDecoration.underline,
),
),
),
),
],
),
),
),
You should not call setState
in your loop, try this:
if (files != null) {
for (var element in files) {
images.add(File(element.path));
}
setState(() {});
}
For your main issue in flutter web instead of Image.file
you need to use Image.memory
, so first change your piker result list to this:
final picker = ImagePicker();
List<Uint8List> images = [];// <----change this
List<int> imageFiles = [];
void _imgFromGallery() async {
List<XFile>? files = await picker.pickMultiImage(
imageQuality: 50,
);
if (files != null) {
for (var element in files) {
images.add(await element.readAsBytes());// <----change this
}
setState(() {});
}
then show it like this:
Image.memory(// <----change this
images[index],
height: 80,
width: 80,
)