I am creating an app that allows user to save small data. I have a json file in my assets folder and I would like to create an app that can write more json data to it. Path: assets/vault.json
vault.json
[
{
"name":"Ash",
"age":"22",
"hobby" : "golf"
},
{
"name":"philip",
"age":"17",
"hobby" : "fishing"
},
{
"name":"charles",
"age":"32",
"hobby" : "drawing"
}
]
However I am stuck at adding more list to the json file.
In my main.dart, I created 3 textfield for input and a button onPress to trigger writeToFile(arg1,arg2,arg3).
Here is what I have tried:
void writeToFile(String hobbyy, String agee, String namee) {
print("Writing to file!");
Map<String, dynamic> content = new Map();
content1 = {name: namee};
content2 = {age: agee};
content3 = {hobby: hobbyy};
content.addAll(content1);
content.addAll(content2);
content.addAll(content3);
print(content); //working fine
}
Future<String> _loadAVaultAsset() async {
return await rootBundle.loadString('assets/vault.json');
}
Future loadVault() async {
String jsonString = await _loadAVaultAsset();
final jsonResponse = json.decode(jsonString);
var add = jsonResponse.toString();
add = add.replaceFirst(new RegExp(r'}]'), "},"+content.toString()+"]");
print(add); //shows the full json string that I want.
//How to add/replace (add) into the json file?
}
although I am getting the json string that I want, I am unable to reflect it in the json file.
Here is my vault_model.dart (incase if there is any use):
class UsersList{
final List<Users> user;
UsersList({
this.user,
});
factory UsersList.fromJson(List<dynamic> parsedJson){
List<Users> entireList = new List<Users>();
entireList = parsedJson.map((i)=>Users.fromJson(i)).toList();
return UsersList(
user: entireList,
);
}
}
class Users{
final String name;
final String age;
final String hobby;
Users({
this.name,
this.age,
this.hobby
});
factory Users.fromJson(Map<String, dynamic> json){
return new Users(
name: json['name'],
age: json['age'],
hobby: json['hobby'],
);
}
}
Please teach me how to replace the old json string with the new string (add) in the assets/vault.json path.
The code which is used to fetch data from the JSON file (see the full code below): Future<void> readJson() async { final String response = await rootBundle. loadString('assets/sample. json'); final data = await json.
fromJson(Map<String, dynamic> json) : this. value = json['value']; Map<String, dynamic> toJson() => {'value': value}; } ... JsonStore jsonStore = JsonStore(); CounterModel counter; loadFromStorage() async { Map<String, dynamic> json = await jsonStore.
Instead of storing in rootBundle
, can you store it in app's file system. Refer here
Since you cannot write to a file in assets during runtime, as mentioned before, store it somewhere else in your local machine. The following code can read from a json file and write to it --
import 'dart:io';
import 'dart:convert';
List<Player> players = [];
void main() async{
print("hello world");
final File file = File('D:/Sadi/../vault.json'); //load the json file
await readPlayerData(file); //read data from json file
Player newPlayer = Player( //add a new item to data list
'Samy Brook',
'31',
'cooking'
);
players.add(newPlayer);
print(players.length);
players //convert list data to json
.map(
(player) => player.toJson(),
)
.toList();
file.writeAsStringSync(json.encode(players)); //write (the whole list) to json file
}
Future<void> readPlayerData (File file) async {
String contents = await file.readAsString();
var jsonResponse = jsonDecode(contents);
for(var p in jsonResponse){
Player player = Player(p['name'],p['age'],p['hobby']);
players.add(player);
}
}
class Player {
late String name;
late String age;
late String hobby;
Player(
this.name,
this.age,
this.hobby,
);
Player.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
hobby = json['hobby'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
data['hobby'] = this.hobby;
return data;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With