我使用downloads_path_provider
软件包写入下载目录。
我设置了它,因为它是推荐的
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
投射AndroidManifest.xml
但是当我尝试写时,出现此错误
E/flutter (26091): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = '/storage/emulated/0/Download/secure-strorage-backup.txt' (OS Error: Permission denied, errno = 13)
这是代码
final file = _localFile;
file.writeAsString('1234 5678\n');
file.writeAsString('1234 5678\n');
File get _localFile {
final path = _downloadsDirectory.path;
return File('$path/secure-strorage-backup.txt');
}
如何写入下载文件夹?
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.myappname">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Secure Storage"
...
这是我如何获得downloadsDirectory
void initState() {
super.initState();
initDownloadsDirectoryState();
}
Future<void> initDownloadsDirectoryState() async {
Directory downloadsDirectory;
try {
downloadsDirectory = await DownloadsPathProvider.downloadsDirectory;
} on PlatformException {
print('Could not get the downloads directory');
}
if (!mounted) return;
setState(() {
_downloadsDirectory = downloadsDirectory;
});
}
答案 0 :(得分:2)
如this答案中所述,您还需要明确询问用户使用外部存储的许可,您可以使用this软件包
更新:
this软件包变得更好,并且得分更高,您可以像这样使用它:
await Permission.storage.request();
Directory downloadsDirectory = await DownloadsPathProvider.downloadsDirectory;
final String path = downloadsDirectory.path;
final File file = File('$path/secure-strorage-backup.txt');
await file.writeAsString('1234 5678\n');
await file.writeAsString('1234 5678\n');
print(await file.readAsString());