• notice
  • Congratulations on the launch of the Sought Tech site

How to use the pickMultiImage of image_picker in flutter to get the image path after selecting multiple images

I am trying to select multiple images, so for this I use pickMultiImage has the method of image_picker.The images are displayed on the screen, but I need their paths so that I can upload using itcloudinary.com.

This is my code

 List<XFile>? _imageFileList3=[];

 Future pickMultipleImage() async {
    if (_imageFileList3!.length==4) {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoginSucessDailog(
                text: 'You can\'t add more than 4 images.',
                title: 'Warning.',
                img: 'assets/img/alert.png');
          });
    } else {
      try {
       var image=await _picker.pickMultiImage();

//here i'll be using cloudinary code


        setState(() {
          _imageFileList3!.addAll(image!);
        });
        print(image);
        print(_imageFileList3!.length);
        
        setState(() {
          isImageLoading=false;
        });
      } on CloudinaryException catch (e) {}

      
    }
  }


This is part of the code I use to upload images on Cloudinary using the cloudinary_public package

 CloudinaryResponse response=await cloudinary.uploadFile(
        CloudinaryFile.fromFile(image!.path,
            resourceType: CloudinaryResourceType.Image),
     );

Show images like this

 addProductsImages() {
    if (_imageFileList3!.length !=0) {
      return SizedBox(
          height: 80,
          width: MediaQuery.of(context).size.width * 0.9,
          child: GridView.builder(
              shrinkWrap: true,
              itemCount: _imageFileList3!.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
             ),
              itemBuilder: (BuildContext context, int index) {
                return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Stack(children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: Image.file(
                          File((_imageFileList3![index].path)),
                          width: MediaQuery.of(context).size.width * 0.35,
                          height: MediaQuery.of(context).size.height * 0.17,
                          fit: BoxFit.cover,
                       ),
                     ),
                      Align(
                          alignment: Alignment.topRight,
                          child: buildCancelIcon(Colors.white, () {
                            setState(() {
                              //_imageFileList!.removeAt(index);
                            });
                          }, Icons.cancel))
                    ]));
              }));
    } else {
      return Padding(
          padding: const EdgeInsets.only(left: 70),
          child:
              Row(crossAxisAlignment: CrossAxisAlignment.center, children: []));
    }
  }

Please help how to do this or is there any way to select multiple images at once and upload them to cloudinary.

uj5u.com enthusiastic netizens replied:

Please refer to the sample code below, users can select up to 5 images

Use these packages

Image selector: ^1.2.4

Flutter Compression: ^0.7.0

How to use the pickMultiImage of image_picker in flutter to get the image path after selecting multiple images

How to use the pickMultiImage of image_picker in flutter to get the image path after selecting multiple images

class PickMultipleImagesScreen extends StatefulWidget {
  const PickMultipleImagesScreen({Key key}) : super(key: key);

  @override
  _PickMultipleImagesScreenState createState()=>
      _PickMultipleImagesScreenState();
}

class _PickMultipleImagesScreenState extends State<PickMultipleImagesScreen> {
  final ValueNotifier<bool> attachMultipleImages=ValueNotifier<bool>(false);
  List compressedPhotosList=["place_holder"];
  int maxImagesCount=5;

  pickPhotos() async {
    List<Media> photosList=[];
    photosList=await ImagesPicker.pick(
      count: (compressedPhotosList !=null &&
              (compressedPhotosList.isNotEmpty) &&
              (compressedPhotosList.length > 1))
          ? (maxImagesCount 1-compressedPhotosList.length)
          : maxImagesCount,
      pickType: PickType.all,
      language: Language.System,
      cropOpt: CropOption(
        aspectRatio: CropAspectRatio(600, 400),
     ),
   );

    if (photosList !=null && photosList.isNotEmpty && photosList.length > 0) {
      for (int i=0; i < photosList.length; i) {
        File photoCompressedFile=
            await compressImage(File(photosList[i].path));
        print("Images List: $photosList");
        print("Path of UnCompressed File: ${photosList[i].path}");
        compressedPhotosList.insert(
          0,
          photoCompressedFile.path.toString(),
       );
        print("Path of Compressed File: ${photoCompressedFile.path}");
        print("Compressed Images List: $compressedPhotosList");
      }
      attachMultipleImages.value=!attachMultipleImages.value;
    }
  }

  Future<File> compressImage(File file) async {
    final filePath=file.absolute.path;
    final lastIndex=filePath.lastIndexOf(new RegExp(r'.png|.jp'));
    final splitted=filePath.substring(0, (lastIndex));
    final outPath="${splitted}_out${filePath.substring(lastIndex)}";

    if (lastIndex==filePath.lastIndexOf(new RegExp(r'.png'))) {
      final compressedImage=await FlutterImageCompress.compressAndGetFile(
          filePath, outPath,
          minWidth: 1000,
          minHeight: 1000,
          quality: 50,
          format: CompressFormat.png);
      return compressedImage;
    } else {
      final compressedImage=await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 1000,
        minHeight: 1000,
        quality: 50,
     );
      return compressedImage;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ValueListenableBuilder<bool>(
        valueListenable: attachMultipleImages,
        builder: (context, snapshot, child) {
          return Scaffold(
            body: (compressedPhotosList !=null &&
                    compressedPhotosList.isNotEmpty &&
                    compressedPhotosList.length > 1)
                ?GridView.builder(
                    itemCount: (compressedPhotosList !=null &&
                            compressedPhotosList.isNotEmpty &&
                            compressedPhotosList.length > 1 &&
                            (compressedPhotosList.length-1==maxImagesCount))
                        ?compressedPhotosList.length-1
                        : compressedPhotosList.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 4.0,
                        mainAxisSpacing: 4.0),
                    itemBuilder: (BuildContext context, int index) {
                      return ((compressedPhotosList[index]=="place_holder") &&
                              compressedPhotosList.length-1 !=maxImagesCount)
                          ? InkWell(
                              onTap: () async {
                                if (compressedPhotosList.length-1 !=
                                    maxImagesCount) {
                                  pickPhotos();
                                }
                              },
                              child: Container(
                                margin: EdgeInsets.all(
                                  5.0,
                               ),
                                width: ScreenUtil().screenWidth,
                                height: ScreenUtil().setHeight(105.0),
                                color: Colors.blueAccent,
                                child:center(
                                  child: Icon(
                                    Icons.add,
                                    size: ScreenUtil().setSp(24.0),
                                    color: Colors.grey,
                                 ),
                               ),
                             ),
                           )
                          : Stack(
                              clipBehavior: Clip.none,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(4.0),
                                  child: Image.file(
                                    File(compressedPhotosList[index]),
                                    fit: BoxFit.fitHeight,
                                    width: ScreenUtil().screenWidth,
                                    height: ScreenUtil().setHeight(105.0),
                                    filterQuality: FilterQuality.low,
                                    errorBuilder: (context, error, stackTrace) {
                                      return Container(
                                        width: ScreenUtil().screenWidth,
                                        height: ScreenUtil().setHeight(105.0),
                                        color: Colors.black,
                                     );
                                    },),
                               ),
                                Positioned(
                                  bottom: 10,
                                  right: 8,
                                  child: InkWell(
                                    onTap: () async {
                                      compressedPhotosList.removeAt(index);
                                      attachMultipleImages.value=
                                          !attachMultipleImages.value;
                                    },
                                    child: CircleAvatar(
                                      radius: 15.0,
                                      backgroundColor: Colors.black45,
                                      child: Icon(
                                        Icons.delete_forever,
                                        color: Colors.white,
                                        size: 20,
                                     ),
                                   ),
                                 ),
                               )
                              ],
                           );
                    },
                 )
                :center(
                    child: InkWell(
                      onTap: () {
                        pickPhotos();
                      },
                      child: Text("Attach Images"),
                   ),
                 ),
         );
        }
     ),
   );
  }
}

Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+