Home > other >  Nothing happens when saving to local app directory? Flutter
Nothing happens when saving to local app directory? Flutter

Time:06-21

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

CodePudding user response:

In newer android versions you can't create a directory or save a file without the specific permissions (Scoped Storage), maybe this is the case. You can check my answers and maybe it can solve this problem ^^

ANSWER 1

ANSWER 2

ANSWER 3

CodePudding user response:

To save the files, please follow below instructions.

find the correct path of the location you want to save by using ext_storage or path_provider. You will need this permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

on Android 10 you need this in your manifest

<application
      android:requestLegacyExternalStorage="true"

on Android 11 use this instead

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

Remember to ask for them using permission_handler

And to store file, please call below method

static Future saveInStorage(
      String fileName, File file, String extension) async {
    await _checkPermission();
    String _localPath = (await ExtStorage.getExternalStoragePublicDirectory(
        ExtStorage.DIRECTORY_DOWNLOADS))!;
    String filePath =
        _localPath   "/"   fileName.trim()   "_"   Uuid().v4()   extension;

    File fileDef = File(filePath);
    await fileDef.create(recursive: true);
    Uint8List bytes = await file.readAsBytes();
    await fileDef.writeAsBytes(bytes);
  }
  • Related