0

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;
 }
1
  • if I may, I'd like to clarify something here quickly: "JSON" itself is literally "JavaScript Object Notation". so a "JSON file", is quite simply "JavaScript Object Notation in a file".. in this scenario, you (1) read the JSON String from a file (jsonFile.readAsStringSync()), (2) parse the resulting String into a Map (json.decode(jsonFileReadAsString)), (3) modify whatever you need to, (4) convert that object back to a String (json.encode(objectAfterEdits)), and then (5) write that String back to the file (jsonFile.writeAsStringSync(newDataString)). Commented Mar 31, 2022 at 11:59

1 Answer 1

2

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));
 }
Sign up to request clarification or add additional context in comments.

2 Comments

this worked but i have other objects which are being empty. is there anyway to just edit the specific data without re-writing the whole json?
No. You have to write the whole JSON every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.