我正在尝试将特定值更新为外部存储中的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;
}
答案 0 :(得分: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));
}