【发布时间】:2020-11-08 19:01:11
【问题描述】:
我将用户收藏夹存储到 json 文件中,但出现以下错误:
未处理的异常:类型“_InternalLinkedHashMap
”不是“other”的“Map ”类型的子类型
我正在将以下数据添加到文件中:
{
3423: {
'ID': 3423,
'Title': 'Jupiter Ascending',
'Image': 'https://...'
}
}
代码是:
File jsonFile;
Directory dir;
String fileName = "Reading.json";
bool fileExists = false;
List<Map> fileContent;
@override
void initState() {
super.initState();
/*to store files temporary we use getTemporaryDirectory() but we need
permanent storage so we use getApplicationDocumentsDirectory() */
getApplicationDocumentsDirectory().then((Directory directory) {
dir = directory;
jsonFile = new File(dir.path + "/" + fileName);
fileExists = jsonFile.existsSync();
if (fileExists)
this.setState(
() => fileContent = json.decode(jsonFile.readAsStringSync()));
});
}
void createFile(Map content, Directory dir, String fileName) {
print("Creating file!");
File file = new File(dir.path + "/" + fileName);
file.createSync();
fileExists = true;
file.writeAsStringSync(json.encode(content));
}
void writeToFile(var key, var value) {
print("Writing to file!");
Map content = {key: value};
if (fileExists) {
print("File exists");
Map jsonFileContent = json.decode(jsonFile.readAsStringSync());
jsonFileContent.addAll(content);
jsonFile.writeAsStringSync(json.encode(jsonFileContent));
} else {
print("File does not exist!");
createFile(content, dir, fileName);
}
this.setState(() => fileContent = json.decode(jsonFile.readAsStringSync()));
print(fileContent);
}
我很困惑,不知道如何解决这个问题。
【问题讨论】: