androidflutterdirectorylocal-storagefile-storage

Nothing happens when saving to local app directory? Flutter


I'm picking an image from gallery, and then I should save it to the App Local Directory, But that directory is never created!

I'm using image_picker and path_provider libraries, and used no permission.

Inside Press Button function:

getImageIntoLocalFiles(ImageSource.gallery); //call getImage function

The getImage function:

Future getImageIntoLocalFiles(ImageSource imageSource) async {

    final ImagePicker _picker = ImagePicker();

    // using your method of getting an image
    final XFile? image = await _picker.pickImage(source: imageSource);

    //debug
    print('${image?.path} ---image path'); //returns /data/user/0/com.ziad.TM.time_manager/cache/image_picker6496178102967914460.jpg

    // getting a directory path for saving
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;

    //debug
    if(image != null) print('$appDocPath ---local directory path'); //return /data/user/0/com.ziad.TM.time_manager/app_flutter

    // copy the file to a new path
    await image?.saveTo('$appDocPath/image1.png');
  }

I don't understand where is the problem as there is no errors and I can't find a documentation explaining this.

com.ziad.TM.time_manager is never actually created


Solution

  • according to flutter's documentation

    getApplicationDocumentsDirectory : On Android, this uses the getDataDirectory API on the context. Consider using getExternalStorageDirectory instead if data is intended to be visible to the user.

    So, by changing getApplicationDocumentsDirectory() to getExternalStorageDirectory() the directory is created and the file is successfully saved!!


    I also found a way to create a new custom folder inside:

    String dirToBeCreated = "<New Folder Name>";
    
        if(baseDir != null) {
          String finalDir = join(baseDir.path, dirToBeCreated);
          var dir = Directory(finalDir);
    
          bool dirExists = await dir.exists();
          if (!dirExists) {
            dir.create(
                /*recursive=true*/); //pass recursive as true if directory is recursive
          }
    

    and don't forget to pass dir.path to saveTo() parameter (a string path not a Directory)