Search code examples
androidjsonflutterdartinsert-update

How to Edit(Update) data in JSON file flutter


I am trying to update specific value to a JSON File in external Storage.

Though I am able to write to the file but It is replacing the whole JSON File with the single data.

// This one is Replacing the whole document with single value

 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));
 }

//this is changing the value temporarily but not writing to the file

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

Solution

  • You need to write the whole question list. Break it into two statements

     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));
     }