You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter读写文件异常:重复写入后读取仍为初始内容的解决

Flutter FilePicker读取文件无法获取更新内容的问题与解决方案

原问题

开发Flutter应用时,将数据库内容导出为JSON文件,修改内容后再次导出,设备本地直接打开文件能看到更新后的内容,但通过FilePicker选择文件读取时,始终只能获取初始写入的内容。手动删除文件后重新操作可正常读取更新内容,但在写入前调用file.delete()无法解决该问题。

相关代码片段

获取写入文件路径

Future<File?> _getBackupDataFile(String pathToTryFirst, ExportData data) async {
    Directory? directory = Directory(pathToTryFirst);
    if (!await directory.exists()) directory = await getExternalStorageDirectory();
    if ((await directory?.exists() ?? false) == false) {
      showErrorDialog(context: context, body: "Unable to find directory to save file.");
      return null;
    }

    return File("${directory?.path}/pm-account-backup.json");
}

文件写入逻辑

Future<void> _writeDataToFile(ExportData data) async {
    try {
      File? file = await _getBackupDataFile('/storage/emulated/0/Download', data);
      if(file == null) { return; }
      await file.writeAsString(jsonEncode(data));
      await showSuccessDialog(context: context, title: "Success", body: "${data.accounts.length} accounts backed up successfully.");
    } catch (e) {
      showErrorDialog(context: context, body: "Failed to write data to file.");
    }
  }

文件选择逻辑

FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
    String path = result.files.single.path ?? '';
    if((path).endsWith(".json")) {
          return File(path);
    }
}

文件读取逻辑

String fileData = await file.readAsString();
print(fileData);

解决方案

问题根源

Android外部存储的机制导致file_picker插件会为选中的文件创建一份缓存,存储在应用专属的缓存目录中。后续读取同名文件时,插件会直接返回缓存版本而非最新的原文件,因此无法获取更新内容。

修复方法

在完成文件读取操作后,调用await file.delete();删除插件生成的缓存文件。这样下次通过FilePicker选择文件时,插件会重新创建包含最新内容的缓存版本,确保读取到的是更新后的文件内容。

内容的提问来源于stack exchange,提问作者Sam Radford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:01:19