late File jsonFile;
late Directory dir;
String fileName = "myJSONfile.json";
bool fileExists = false;
Map fileContent = <String, String>{};
//late Map<String, String> fileContent;
//late Map<String, String> fileContent = {};
//var fileContent = <String, String>{};
@override
void initState() {
super.initState();
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<String, String> 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 writeFile(String key, String value) {
print("Writing to file!");
Map<String, String> content = {key: value};
if (fileExists) {
print("File exists");
Map<String, String> jsonFIleContent =
json.decode(jsonFile.readAsStringSync());
jsonFIleContent.addAll(content);
jsonFile.writeAsStringSync(json.encode(jsonFIleContent));
} else {
print("FIle does not exists!");
createFile(content, dir, fileName);
}
this.setState(() => fileContent = json.decode(jsonFile.readAsStringSync()));
}
Hey I'm new on flutter and I'm try to save data with JSON file and read it again but it doesn't work
This is the error: (flutter I/flutter ( 4140): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>')
I've searched on the internet but I didn't find any answer, can someone tell what that error and how can I solve it?