FilePicker- path[] - list empty

552 views Asked by At

I am working on a view where the user can click on a button - Picture, the user should be able to then select one image. Then, the user might want to click again and to select an other image. The second image should be added to the previous one. Both of the images should be displayed. Below, you will see several test I have done, but none of them work. In the first case, I can not store the image one by one. In the second case, I am getting an error message "The following FileSystemException was thrown resolving an image codec: Cannot open file, path = '[]' (OS Error: No such file or directory, errno = 2)"

I have updated my code. I have added print at two different location of the code. The first Print, display correct result. The second one display that all values are empty or null. It is very strange. I do not understand why.

If you can help me it would be great.

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';

class FilePickerDemo extends StatefulWidget {
  @override
  _FilePickerDemoState createState() => _FilePickerDemoState();
}

class _FilePickerDemoState extends State<FilePickerDemo> {
  //FirebaseStorage storage = FirebaseStorage.instance;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  late String _fileName;
  List<PlatformFile>? _paths;
  List<PlatformFile>? _allFile;
  bool _loadingPath = false;
  bool _multiPick = true;
  List<String>? extensions;
  FileType _fileType = FileType.media;
  List<File> f = [];
  var image;
  List<File> filesGB =[];


  String _file_Type_pdf_image = '';

  void _openPictureFileExplorer() async {
    setState(() => _loadingPath = true);

   /*
    FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

    if(result != null) {
      List<File> files = result.paths.map((path) => File(path!)).toList();
    } else {
      // User canceled the picker
    }

    */

    try {
      //####################################################
      // _paths = (await FilePicker.platform.pickFiles(
      //   type: _fileType,
      //   allowMultiple: _multiPick,
      // ))
      //     ?.files;

      //####################################################

      FilePickerResult? _paths = await FilePicker.platform.pickFiles(
        type: _fileType,
        allowMultiple: _multiPick,
      );

      if (_paths != null) {
        List<File> filesGB = _paths.paths.map((path) => File(path!)).toList();
        setState(() {});
        print('File Name:'+filesGB.toString());
        print ('# record:'+ filesGB.length.toString());
        print ('Empty?: '+filesGB.isEmpty.toString());

      }
/*
      //######################################################
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: _fileType,
      );
      if (result != null) {
        List<File> filesGB = result.paths.map((path) => File(path!)).toList();
        setState(() {});
        print('mon Fichier:'+filesGB.toString());
      }
      //####################################################

      */

    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print('$ex');
    }

    //if (!mounted) return;

    setState(() {
      _loadingPath = false;
      //print(_paths!.last.name);
      print('File Name:'+filesGB.toString());
      print ('# record:'+ filesGB.length.toString());
      print ('Empty?: '+filesGB.isEmpty.toString());
      _fileName = _paths != null ?
      _paths!.map((e) => e.name).toString() : '...';
    });
  }
/*
  void _openDocumentFileExplorer({fileType: FileType.custom}) async {
    setState(() => _loadingPath = true);
    extensions == ['pdf', 'PDF'];

    try {
      _paths = (await FilePickerDemo.platform.pickFiles(
          type: fileType,
          allowMultiple: true, //_multiPick,
          allowedExtensions: ['pdf', 'doc']
      ))
          ?.files;
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print('$ex');
    }

    if (!mounted) return;

    setState(() {
      _loadingPath = false;
      //  print(_paths!.last.name);
      _fileName = _paths != null ?
      _paths!.map((e) => e.name).toString() : '...';

      if (_paths != null) {
        _allFile!.addAll(_paths!);
        // print(_allFile);
      }
    });
  }

  void _clearCachedFiles() {
    FilePickerDemo.platform.clearTemporaryFiles().then((result) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: result! ? Colors.green : Colors.red,
          content: Text((result
              ? 'Temporary files removed with success.'
              : 'Failed to clean temporary files')),
        ),
      );
    });
  }

  */

  /*
  void imagem() async {
    PickedFile? picked = await ImagePicker().getImage(
        preferredCameraDevice: CameraDevice.front, source: ImageSource.gallery);
    setState(() {
      image = File(picked!.path);
      Image.file(image);
    });}
*/
  // Select and image from the gallery or take a picture with the camera
  // Then upload to Firebase Storage

  /*
  Future<void> _upload() async {

    try {

      final String fileName = _fileName;
      File imageFile = File(_paths.toString());

      try {
        // Uploading the selected image with some custom meta data
        await storage.ref(fileName).putFile(
            imageFile,
            );

        // Refresh the UI
        setState(() {});
      } on FirebaseException catch (error) {
        print(error);
      }
    } catch (err) {
      print(err);
    }
  }


  */


  // Delete the selected image
  // This function is called when a trash icon is pressed
  void _delete(int index) {
    if (_paths != null || _paths!.length > 1) {
      _paths!.removeAt(index);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: const Text('File Picker example app'),
        ),
        body: Center(
            child: Padding(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(top: 20.0),

                      //#############
                      //Affiche card avec button pour selectionner type de piece jointe - photo ou docuent ou audio record
                      child: Card(
                          child:
                          Container(
                            // color: Colors.red,
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //  color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.access_alarm_outlined),
                                            Text('TEST'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      _file_Type_pdf_image = 'pdf';
                                      //imagem;
                                    },
                                  ),
                                ),
                                //Attachement
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //  color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.attach_file),
                                            Text('Attachement'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      _file_Type_pdf_image = 'pdf';
                                      //_openDocumentFileExplorer();
                                    },
                                  ),
                                ),

                                //Photo
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //   color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.add_a_photo_rounded),
                                            Text('Photo'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      _file_Type_pdf_image = 'jpeg';
                                      _openPictureFileExplorer();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          )),
                    ),


                    Builder(
                      builder: (BuildContext context) =>
                      _loadingPath ?
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10.0),
                        child: const CircularProgressIndicator(),
                      )
                          : _paths != null && _paths!.isNotEmpty
                          ? Container(
                        padding: const EdgeInsets.only(bottom: 30.0),
                        height:
                        MediaQuery
                            .of(context)
                            .size
                            .height * 0.50,
                        child: Scrollbar(
                          child: _paths!.isNotEmpty ?
                          ListView.separated(
                            itemCount:
                            _paths != null && _paths!.isNotEmpty
                                ? _paths!.length
                                : 1,
                            itemBuilder:
                                (BuildContext context, int index) {
                              final bool isMultiPath =
                                  _paths != null && _paths!.isNotEmpty;
                              final String name =
                              _paths!
                                  .map((e) => e.name)
                                  .toList()[index];

                              final path = _paths!
                                  .map((e) => e.path)
                                  .toList()[index]
                                  .toString();

                              return Container(
                                height: 114,
                                child: Card(
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(15.0),
                                  ),
                                  elevation: 10,
                                  child: ClipPath(
                                    clipper: ShapeBorderClipper(
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius
                                                .circular(15))),
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment
                                          .center,
                                      mainAxisAlignment: MainAxisAlignment
                                          .start,
                                      children: [

                                        Container(
                                          height: 113, width: 113,
                                          child: _file_Type_pdf_image == 'pdf'
                                              ?
                                          Image.asset("assets/logo_pdf.png")

                                          // fit: BoxFit.fill,
                                          // width: double.infinity,):
                                              : Image.file(File(f.toString()),
                                            fit: BoxFit.fill,
                                            width: double.infinity,),
                                        ),
                                        Expanded(
                                          child: Padding(
                                            padding: const EdgeInsets.all(
                                                10.0),
                                            child: Text(name,
                                              style: TextStyle(
                                                  fontWeight: FontWeight
                                                      .bold),),
                                          ),
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.only(
                                              right: 25.0),
                                          child: IconButton(onPressed: () {
                                            //delete a record and the card displaying this record
                                            _delete(index);
                                          },

                                            icon: Icon(Icons.delete,
                                              color: Colors.red,),),
                                        )
                                      ],
                                    ),
                                  ),
                                  //subtitle: Text(path),
                                ),
                              );
                            },
                            separatorBuilder:
                                (BuildContext context, int index) =>
                            const SizedBox(),) : Text(
                              "Text to display when _paths is empty"),),)
                          : filesGB.isEmpty? SizedBox(child:image= (Image.file(File(filesGB.toString())))): Text('ALL Empty'),//child: Text('No documents')),
                    ),
                  ],
                ),
              ),
            )),
      ),
    );
  }
}
1

There are 1 answers

1
Farhan Aslam On

I didn't go through your code but still, I can suggest you first update your Package or try with a different one. Use a list to store Images data. Test it on a real device.