【问题标题】:How to Edit(Update) data in JSON file flutter如何在 JSON 文件中编辑(更新)数据
【发布时间】:2019-11-10 23:13:29
【问题描述】:

我正在尝试将特定值更新为外部存储中的 JSON 文件。

虽然我可以写入文件,但它正在用单个数据替换整个 JSON 文件。

//这个是用单个值替换整个文档

 Future setBookmark(int questionId, String isBookmark) async {
   Map<String, dynamic> content = {questionId.toString(): isBookmark};
   var dir = await getExternalStorageDirectory();

   var testdir = new Io.Directory('${dir.path}/BCS/bcs.json');
   File jsonFile = File(dir.path + "/BCS/" + "bcs.json");

   Map<String, dynamic> jsonFileContent = 
     json.decode(jsonFile.readAsStringSync());
   jsonFileContent.addAll(content);
   jsonFile.writeAsStringSync(json.encode(_listQuestions
     .firstWhere((question) => question.id == questionId)
     .bookmark = isBookmark));
 }

//这是临时更改值但不写入文件

 Future setBookmark(int questionId, String isBookmark) async {
    _listQuestions
        .firstWhere((question) => question.id == questionId)
        .bookmark = isBookmark;
 }

【问题讨论】:

    标签: android json flutter dart insert-update


    【解决方案1】:

    您需要编写整个问题列表。把它分成两个语句

     Future setBookmark(int questionId, String isBookmark) async {
        // update the list
        _listQuestions
            .firstWhere((question) => question.id == questionId)
            .bookmark = isBookmark;
        // and write it
        jsonFile.writeAsStringSync(json.encode(_listQuestions));
     }
    

    【讨论】:

    • 这行得通,但我还有其他空的对象。无论如何只编辑特定数据而不重写整个json?
    • 没有。您必须每次都编写整个 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多