如何使用Flutter编辑或删除Android设备中的文件?

问题描述 投票:0回答:1

我想从文件选择器包中编辑或删除文件。但它只是编辑或删除缓存内的文件,而不是真正的文件。我的文件扩展名是 .json

我尝试使用文件选择器包选择文件

Future<String> pickFile() async {
    result = await FilePicker.platform
        .pickFiles(type: FileType.custom, allowedExtensions: ['json']);

    if (result != null) {
      String filePath = result!.files.single.path!;
      String fileContent = await _readFile(filePath);
      setState(() {
        fileName = result!.files.single.name;
      });
      // Olah data JSON
      try {
        jsonData = json.decode(fileContent);
        // Lakukan sesuatu dengan objek jsonData di sini
        debugPrint(jsonData.toString());
        if (jsonData != null) {
          setState(() {
            noKwitansi = jsonData!['receipt_number'] == null
                ? ''
                : jsonData!['receipt_number'].toString();
          });
          jsonData!['isPrint'] = true;
          String updatedJson = json.encode(jsonData);

          await saveUpdatedJsonToFile(filePath, updatedJson);
        }
      } catch (e) {
        // Handle kesalahan pengolahan JSON
        print('Error parsing JSON: $e');
      }
      // debugPrint(fileContent);
      return fileContent;
    } else {
      return '';
    }
  }

这是 saveupdatejson 函数

Future<void> saveUpdatedJsonToFile(
      String filePath, String updatedJson) async {
    try {
      await File(filePath).writeAsString(updatedJson);
      print('File berhasil disimpan!');
    } catch (e) {
      print('Error saving file: $e');
    }
}

这是readFile函数

Future<String> _readFile(String filePath) async {
    try {
      String fileContent = await File(filePath).readAsString();
      return fileContent;
    } catch (e) {
      // Handle kesalahan membaca file
      debugPrint('Error reading file: $e');
      return '';
    }
}

但是当我更改 json 文件中的数据时,更改的 json 文件位于缓存文件中,而不是原始文件中。原始文件存储在下载文件夹中。

android flutter storage
1个回答
0
投票

Android 需要使用存储访问框架来访问应用程序沙箱之外的文件。这意味着您只能使用具有读/写权限的 URI 来操作文件。

这是我为选择器库找到的:

保存示例:

String? outputFile = await FilePicker.platform.saveFile(
  dialogTitle: 'Please select an output file:',
  fileName: 'output-file.pdf',
);

if (outputFile == null) {
  // User canceled the picker
}

参考:https://github.com/miguelpruivo/flutter_file_picker

© www.soinside.com 2019 - 2024. All rights reserved.