I've a flutter app with audio files downloaded from network. I want to download an audio file to my devices Downloads folder to make it usable for later use like Making it a Ringtone or similar.
Previously I used WRITE_EXTERNAL_STORAGE permission via permission handler package's Permission.storage.
From their doc,
As of Android SDK 30 (Android 11) the WRITE_EXTERNAL_STORAGE permission is considered a high-risk or sensitive permission. There for it is required to declare the use of these permissions if you intend to release the application via the Google Play Store.
So, to save file on Downloads folder, I need MANAGE_EXTERNAL_STORAGE (via Permissions. manageExternalStorage). But when I add this permission and submit my app, the update is rejected via google saying that this is not a core functionality of my add and I should use less risky APIs to access data.
So, if I target API 33 or above, how can I download an audio file to my Android devices Downloads folder?
I faced the same situation and found a solution that might be helpful. Instead of relying on the MANAGE_EXTERNAL_STORAGE permission, I chose to directly assign the path '/storage/emulated/0/Download' to save the files.
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
static Future saveFile(String fileName, List<int> bytes) async {
Directory? directory;
File? file;
try {
if (defaultTargetPlatform == TargetPlatform.android) {
//downloads folder - android only - API>30
directory = Directory('/storage/emulated/0/Download');
} else {
directory = await getApplicationDocumentsDirectory();
}
bool hasExisted = await directory.exists();
if (!hasExisted) {
directory.create();
}
//file to saved
file = File("${directory.path}${Platform.pathSeparator}$fileName.pdf");
if (!file.existsSync()) {
await file.create();
}
await file.writeAsBytes(bytes);
} catch (e) {
if (file != null && file.existsSync()) {
file.deleteSync();
}
rethrow;
}
}
This solution worked for me; I hope it proves useful in solving your issue as well.
Apparently, on Android>=33, to write file on external storage, you will not need any permissions at all!
More recent versions of Android rely more on a file's purpose than its location for determining an app's ability to access, and write to, a given file. In particular, if your app targets Android 11 (API level 30) or higher, the WRITE_EXTERNAL_STORAGE permission doesn't have any effect on your app's access to storage. This purpose-based storage model improves user privacy because apps are given access only to the areas of the device's file system that they actually use.
https://developer.android.com/training/data-storage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With