flutterdartfirebase-storagefilepicker

Flutter Firebase: How to upload multiple images?


I've this Button to select images:

IconButton(
            onPressed: () async {
              final results = await FilePicker.platform.pickFiles(
                allowMultiple: true,
                type: FileType.custom,
                allowedExtensions: ['png', 'jpg'],
              );
              if (results == null) {
                ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                    content: Text("No Image selected")
                ),
                );
                return null;
              }

              final path = results.files.single.path!;
              final fileName = results.files.single.name;
              final docID = widget.docID;

                storage
              .uploadFile(path, fileName, docID)
              .then((value) => print('Done'));
            },

          icon: Icon(),
        ),

...then the upload function:

Future<void> uploadFile(

String filePath,
String fileName,
String docID,
) async {
  File file = File(filePath);
  try {

    await storage.ref('images/test/$docID/$fileName').putFile(file);
  } on firebase_core.FirebaseException catch (e) {
    print(e);
  }
}

This works with single images, now i want to select and upload multiple files. The selecting works already, but how can i upload them?

I tried to save the files as a list, but have no idea how to continue: List files = results.paths.map((path) => File(path!)).toList();


Solution

  •     IconButton(
                    onPressed: () async {
                      final results = await FilePicker.platform.pickFiles(
                        allowMultiple: true,
                        type: FileType.custom,
                        allowedExtensions: ['png', 'jpg'],
                      );
                      if (results == null) {
                        ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                            content: Text("No Image selected")
                        ),
                        );
                        return null;
                      }
                      final List<String> filePaths = results.paths!;
                      for (String path in filePaths) {
                      final fileName = path.split('/').last;
                      final docID = widget.docID;
    
                     await storage.uploadFile(path, fileName, docID);
        }
      },
        
                  icon: Icon(),
                ),