我正在创建一个允许用户保存小数据的应用程序。我的资产文件夹中有一个json文件,我想创建一个可以向其中写入更多json数据的应用。路径:assets / vault.json
vault.json
[
{
"name":"Ash",
"age":"22",
"hobby" : "golf"
},
{
"name":"philip",
"age":"17",
"hobby" : "fishing"
},
{
"name":"charles",
"age":"32",
"hobby" : "drawing"
}
]
但是我仍然坚持在json文件中添加更多列表。
在main.dart中,我创建了3个用于输入的文本字段和一个onPress按钮来触发writeToFile(arg1,arg2,arg3)。
这是我尝试过的:
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?
}
尽管我得到了想要的json字符串,但无法在json文件中反映出来。
这是我的vault_model.dart(以防万一):
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'],
);
}
}
请教我如何在assets / vault.json路径中用新字符串(添加)替换旧的json字符串。