简体   繁体   中英

Unable to create app directory in flutter

I am building and flutter app which need to create it's own folder or directory in device but i am unable to do that here is my code to create that folder

Future <io.Directory> get getExternalVisibleDir async{
    try {
      if (await io.Directory('/storage/emulated/0/myFolder').exists()) {
        final externalDir = io.Directory('/storage/emulated/0/myFolder');
        return externalDir;
      } else {
        await io.Directory('/storage/emulated/0/myFolder').create(
            recursive: true);
        final externalDir = io.Directory('/storage/emulated/0/myFolder');
        return externalDir;
      }
    }catch(e){
      print("Unable to create directory");
    }
  }

here is my menifest permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
   <application
        android:label="data_encryption"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize"
            android:requestLegacyExternalStorage="true"
            >

and here is my permission handler

 requestStoragePermission() async{
    if(!await Permission.storage.isGranted){
      PermissionStatus result = await Permission.storage.request();
      if(result.isGranted){
        setState(() {
          _isgranted =true;
        });
      }else{
        _isgranted=false;
      }
    }
  }

You might be able to use a Flutter package that does some of the work for you. With path_provider you're able to use Directory appDocDir = await getApplicationDocumentsDirectory(); to get an application directory.

https://pub.dev/packages/path_provider

I'm not sure what your exact use-case is, but if it is saving a file in a directory and retrieving it later, this probably is your best bet.

Future <io.Directory> get getExternalVisibleDir async{
    io.Directory Directory;
    try {
      if (await Permission.storage.isGranted) {
        Directory = await getExternalStorageDirectory();
        print(Directory.path);
        return Directory;
      } else {
        requestStoragePermission();
      }
    }catch(e){
      print("Unable to create directory");
    }
  }

this worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM