【问题标题】:Can't write to file in flutter无法在颤动中写入文件
【发布时间】:2021-10-16 04:50:56
【问题描述】:

这是制作和写入文件的代码,我可以写入临时文件,但由于某种原因,其他任何东西似乎都不起作用。

Directory? dir;
await Permission.storage.request();
if (!await Permission.storage.isGranted) return;
String? dirPath = await FilePicker.platform.getDirectoryPath();
if (dirPath == null) return;
dir = await Directory(dirPath).create(recursive: true);
for (var pdf in selected) {
  var bytes = base64Decode(pdf.pdfData.replaceAll('\n', ''));
  File savedFile = await File(dir.path +
      '/Receipt-' +
      DateTime.now().millisecondsSinceEpoch.toString() +
      '.pdf')
    .create(recursive: true);
  savedFile.writeAsBytes(bytes.buffer.asUint8List());
}

这是完整的错误

E/flutter (21592): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot create file, path = '/storage/emulated/0/Receipts/Receipt-1634356377430.pdf' (OS Error: Operation not permitted, errno = 1)
E/flutter (21592): #0      _File.create.<anonymous closure> (dart:io/file_impl.dart:255:9)
E/flutter (21592): #1      _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter (21592): #2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (21592): <asynchronous suspension>
E/flutter (21592): #3      PocketLoaded.downloadPDFs (package:receipts/cubit/pocket_state.dart:54:24)
E/flutter (21592): <asynchronous suspension>

我的清单标签内的清单中也有这个

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果我做错了,我应该如何写入用户可以在应用程序之外访问的文件?

【问题讨论】:

  • 使用 Android 10+ 设备?
  • Cannot create file, path = '/storage/emulated/0/Receipts/Receipt-1634356377430.pdf' (OS Error: Operation not permitted, errno = 1)

标签: android ios flutter dart


【解决方案1】:

在 android 10 之后情况发生了变化。您需要在 AndroidManifest.xml 中添加此权限。

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

获取权限使用

if (await Permission.manageExternalStorage.request().isGranted) {...}

注意:此权限被认为有很大风险,因此 Play 商店将拒绝您的应用,除非它是您应用的核心功能。

这就是谷歌所说的

核心功能被定义为应用的主要目的。没有 这个核心功能,应用程序“损坏”或呈现不可用。这 核心功能,以及构成此的任何核心功能 核心功能,必须在显着位置记录和推广 应用的描述。

如果您打算在外部目录中创建文件但找不到它,那是因为您必须告诉设备刷新文件。所以我建议使用这个package 并将你新创建的文件路径传递给它,或者如果你想用 kotlin 手动执行这里的代码

    private fun broadcastFileUpdate(path: String) {
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(File(path))))
        println("updated!")
    }

【讨论】:

  • 因此,如果我希望能够编写用户可以从应用程序外部访问的文件,我需要管理外部存储权限,这可能不会让我进入 Playstore?
  • 是的,除非它是一种真正需要它的应用程序。 (例如防病毒软件、文件管理器)。您可以为此将文件存储在Documents 目录中(不需要管理外部存储权限)。
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多