Creating a new sharable text file using Flutter in Android 10 and above

740 views Asked by At

Starting from API 29 (Android 10), Scoped Storage was introduced. Earlier I was able to directly create a sharable file and write in it using this in Flutter:

File f = File("/storage/emulated/0/MyApp/myFile.txt");
await f.writeAsString(contents);

But with privacy changes now it seems impossible to do the same in Android 10 even after I give the Storage permission.

According to documentation,

Move any shared non-media files to an app-dedicated subdirectory of the Downloads/ directory.

My questions are:

  • Can I still create a file in /storage/emulated/0/MyApp/myFile.txt, if yes how?
  • If not, then can I create a file in /storage/emulated/0/Download/MyApp/myFile.txt directly from Flutter without Platform code?
  • If I need to use platform specific code, is using file picker the only option for txt file?

Also I don't want to use android:requestLegacyExternalStorage="true" because then my app won't work for Android 11.

2

There are 2 answers

0
Rob On

Unfortunately it does not seem this has been implemented in Flutter yet to account for the new scoped storage changes. There is an open issue on GitHub: https://github.com/flutter/flutter/issues/35783

2
Ankit Sangwan On

The right solution will be to use android:requestLegacyExternalStorage="true". About the part that it won't work on android 11. That's not the case I think. Just add android:requestLegacyExternalStorage="true" to your AndroidManifest file and in build.gradle change targetSdkVersion 29 whereas keeping compileSdkVersion 30. This should work fine.