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

4

5

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.

Ddt answered 3/8, 2021 at 20:28 Comment(0)
A
10

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

Aragonite answered 20/10, 2021 at 10:38 Comment(2)
The github link you shared is multi_image_picker, but your code use image_picker.Etiolate
Its name of my project but i used the image_picker libarary for selecting multiple images. You can check i wrote image_picker here and in github link same library in pubspec.yaml file.Aragonite
C
1

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

Chemisorb answered 3/8, 2021 at 21:16 Comment(0)
H
0

Include image_picker dependency in pub.dev

Code to get multiple images,

class ImagePickerUtil {
   static final ImagePicker _picker = ImagePicker();

   static Future<List<File>> getImages() async {
     final pickedFiles = await _picker.pickMultiImage(imageQuality: 100);
     if (pickedFiles != null && pickedFiles.isNotEmpty) {
       return pickedFiles.map((xFile) => File(xFile.path)).toList();
     }
     return [];
   }
}

Call this like,

GestureDetector(
  onTap: () async {
    selectedImages = await ImagePickerUtil.getImages();
    widget.selectedImageCallback?.call(selectedImages);
  },
child: yourWidgetWhichHasToCallMultipleImage,

Note if you are using web use Image.network, to get the image for Android or iOS, Image.file will work

if (selectedPhotos.isEmpty)
              UploadPhotosContainer(
                selectedImageCallback: (selectedImages) {
                  selectedPhotos = selectedImages;
                  setState(() {});
                },
              )
            else
              GridView.builder(
                shrinkWrap: true,
                itemCount: selectedPhotos.length + 1,
                gridDelegate:
                    const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 4),
                itemBuilder: (BuildContext context, int index) {
                  if (index == selectedPhotos.length) {
                    return Column(
                      children: [
                        GestureDetector(
                          onTap: () async {
                            List<File> newImages =
                                await ImagePickerUtil.getImages();
                            selectedPhotos.addAll(newImages);
                            setState(() {});
                          },
                          child: Container(
                            height: 80,
                            width: 80,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                border: Border.all(
                                  color: AppColors.yellowColor,
                                )),
                            padding: const EdgeInsets.only(
                                // right: 10,
                                // bottom: 10,
                                ),
                            child: const Icon(
                              CupertinoIcons.add,
                              color: AppColors.yellowColor,
                            ),
                          ),
                        ),
                      ],
                    );
                  } else {
                    return Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Container(
                            height: 100,
                            width: 100,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            padding: const EdgeInsets.only(
                              right: 10,
                              bottom: 10,
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(10),
                              child: Image.file(
                                selectedPhotos[index],
                                height: 100,
                                width: 100,
                                fit: BoxFit.cover,
                              ),
                            )),
                        Positioned(
                          right: 2,
                          top: -7,
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                selectedPhotos.removeAt(index);
                              });
                            },
                            child: const Icon(
                              CupertinoIcons.clear_circled,
                              color: AppColors.redColor,
                              size: 20,
                            ),
                          ),
                        )
                      ],
                    );
                  }
                },
              ),

This code will initially show a container, on whose tap we can get multiple images, once we got it, you can show them, here I have added + container to append the images if user wants to add other images also.Cross Icon will remove the image.

NOTE: I have used callBack cause UPloadContainer is in another file.

Here is the output.

Initial Screen Output after selecting multiple images Appending more image Removing some image

Husain answered 29/10 at 10:58 Comment(0)
S
-2

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.

Slily answered 3/8, 2021 at 21:9 Comment(3)
i use http and dio package and this package have conflict with their versionDdt
You can find a package version that is compatible with all 3 packages by removing all 3 packages and doing a pub add <package_name> on all packages but start with the file_picker package. Alternatively you can use file_picker package and that is compatible with dio & http because i use that myself. Here are the packages i use, hope it helps. file_picker: ^3.0.2+2 dio: ^4.0.0 http: ^0.13.2 Use that and FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true, type: FileType.image);Slily
The type has been set to image to it filters only the images out for you. Hope this can helpSlily

© 2022 - 2024 — McMap. All rights reserved.