how to pick multiple images from gallery and store them in array in flutter?

Viewed 10210

i used image_picker package in my app and it works fine for one image but now i want to use it for multiple images and store them in an array as File. any idea could be greate.

3 Answers

Add dependecy of image_picker:

       image_picker: ^0.8.4+3

Then make a method for selectImages():

      final ImagePicker imagePicker = ImagePicker();
      List<XFile>? imageFileList = [];

      void selectImages() async {
         final List<XFile>? selectedImages = await 
                imagePicker.pickMultiImage();
           if (selectedImages!.isNotEmpty) {
              imageFileList!.addAll(selectedImages);
           }
          print("Image List Length:" + imageFileList!.length.toString());
          setState((){});
      }

Create a builder for showing selected Images:

     return Scaffold(
          appBar: AppBar(
          title: Text('Multiple Images'),
         ),
        body: SafeArea(
           child: Column(
             children: [
                 ElevatedButton(
                    onPressed: () {
                      selectImages();
                  },
                 child: Text('Select Images'),
               ),
               Expanded(
                  child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: GridView.builder(
                        itemCount: imageFileList!.length,
                       gridDelegate: 
                          SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 3),
                          itemBuilder: (BuildContext context, int index) {
                           return Image.file(File(imageFileList![index].path), 
                        fit: BoxFit.cover,);
                     }),
                 ),
               ),
             ],
            ),
          ));

Complete Source code available in github link...

https://github.com/NishaJain24/multi_image_picker

you should use this

 //add this to pubspec.yaml
     multi_image_picker: ^4.7.14
  //add those to the dart file
     import 'package:flutter/material.dart';
     import 'package:multi_image_picker/multi_image_picker.dart';
     import 'dart:async';
 //add a button then in onPressed do this
MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: images,
        materialOptions: MaterialOptions(
          actionBarTitle: "FlutterCorner.com",
        ),
      );

for further infos check this

https://medium.com/@fluttercorner/how-to-select-multiple-images-with-flutter-8fe8e4c78d08

The documentation covers that in here .

final List<XFile>? images = await _picker.pickMultiImage(source: ImageSource.gallery);

That saves it in a list of XFile. There are some platform specific implementation you have to go through so dont miss that. Just have a look at the documentation.

Related