'How to save file to Android/Media on flutter
Been trying all day for the best way to create an app specific folder on anroid 11 devices.
I tried /storage/0/emulated/Android/data/com.talkmia.app/files from path_provider plugin as well as /storage/0/emulated/Android/data/com.talkmia.app/ but app data gets cleared after uninstall and i think android:hasFragileData is useless because it'd only prompt if the app was uinstalled the normal way and it also keeps flutter's own extra data.
I did try SAF too with the saf packages but turns out you can't request access to root-storage and it doesn't make sense to ask users to create the folder then grant permission for that folder.
My only option now is to do it just like WhatsApp does it own. Create it in the Android/Media which i'm finding it hard to do. I've read a number of SO posts as well as Github Issues some suggesting MediaStore API while another suggested using the Context::getExternalMediaDirs which would create the app directory in the Android/Media.
Sighs! My Question now is how can get this Context::getExternalMediaDirs done in dart/flutter. I'd really like not to write platform code 😩😩.
Solution 1:[1]
Using this package : path_provider
Step 1: Get the commonly used file path
Future<String> getFilePath() async {
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); // 1
String appDocumentsPath = appDocumentsDirectory.path; // 2
String filePath = '$appDocumentsPath/demoTextFile.txt'; // 3
return filePath;
}
Step 2: Write content and save the file
void saveFile() async {
File file = File(await getFilePath()); // 1
file.writeAsString("demo file : demoTextFile.txt"); // 2
}
Step 3: Read the file
void readFile() async {
File file = File(await getFilePath()); // 1
String fileContent = await file.readAsString(); // 2
print('File Content: $fileContent');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Furkan |
