Title: Delete key in Json File
Tags: json;flutter;dart
Question: I save data in a Json file. Now I would like to implement the option, to delete data out of the file. I know how to delte the values of a key, but I do not know, how to delete the key (together with the values) out of the Json file.
I tried this:
fileContent.remove('key');
But that doesn't worked.
This is my code to create, read and write to the Json file:
File jsonFile;
Directory dir;
String fileName = "MyFile.json";
bool fileExists = false;
Map<String, dynamic&gt; fileContent;
void createFile(Map<String, dynamic&gt; 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(String key, dynamic value) {
print("Writing to file!");
Map<String, dynamic&gt; content = {key: value};
if (fileExists) {
print("File exists");
Map<String, dynamic&gt; 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(() =&gt; fileContent = json.decode(jsonFile.readAsStringSync()));
print(fileContent);
Thanks for your help!
Comment: I have no clue how to delete the key. I am new to coding & flutter...

Comment: @JoãoSoares I added my attempt based on Sagar's help, but that doesn't worked

Comment: Please share your attempt at deleting the key and show us the issue you are facing. StackOverflow is not a coding service.

Comment: Adding a sample of your json file would help us understand what you want to do.

Comment: don't deal with it as a json file you need to view it as a text file and you can use normal string manipulation functions

Comment: just check if this post works for you
https://stackoverflow.com/questions/17038512/delete-selected-keys-from-dart-map



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:01/28/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<json><flutter><dart>', 'Title': 'Delete key in Json File', 'ViewCount': 1034, 'id': 59945247, 'user_AboutMe': None, 'user_AccountId': 9232122.0, 'user_DisplayName': 'Daniel', 'user_Reputation': 91.0, 'user_Views': 30.0, 'user_id': 6857879.0}}