Flutter Path_provider's getExternalStorageDirectory() returns '/storage/emulated/0/Android/data/com.example.myApp/files', but it is not external dir

89 Views Asked by At

Path_provider's getExternalStorageDirectory() on Android returns '/storage/emulated/0/Android/data/com.example.myApp/files', but it is not external directory. It should return something like '/storage/emulated/0/'.

How can I get this directory without hardcoding?(Because different phones will have different directories)

I tried to add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>

but in anyway it returns app's directory, not root directory

1

There are 1 best solutions below

2
Vettiyanakan On

The directory path returned by getExternalStorageDirectory() might not directly point to the root of the external storage directory due to changes in Android's storage handling in recent versions.

To access the root of the external storage directory without hardcoding the path, you can use the android.os.Environment class to get the external storage directory.

Try this:

import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<String> getExternalStorageDirectory() async {
  if (Platform.isAndroid) {
    Directory? directory = await getExternalStorageDirectory();
    if (directory != null) {
      return directory.parent!.path; // Parent directory should be the root of external storage
    }
  }
  return '';
}

refer also.

for read.