如何在flatter中更新本地json字段
我不熟悉flutter和dart,我读了很多web文章和文档,但没有弄清楚如何更新JSON字段,我有一个本地JSON文件,比如如何在flatter中更新本地json字段,json,flutter,dart,Json,Flutter,Dart,我不熟悉flutter和dart,我读了很多web文章和文档,但没有弄清楚如何更新JSON字段,我有一个本地JSON文件,比如 { "category": "Happiness", "quotes":[ { "quote":"I hope you will find a reason to smile", "favorite":false }, { "quote":"Sometimes your joy is the source of your smile, but
{
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}]}
我想将JSON文件中已归档的收藏夹更新为true是否有任何方法可以做到这一点您可以在JSON中的
quotes
列表上使用forEach循环,并在其中将favorite
设置为true
。我假设您使用jsonDecode
或JSON.decode>将String
数据解析为JSON
如果没有,下面是一个关于如何在Dart中解析JSON数据的示例
考虑以下代码-
Map<String, dynamic> jsonData = {
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}
]};
(jsonData["quotes"] as List<dynamic>).forEach((item) {
item["favorite"] = true;
});
首先将这个json数组带到任何变量,然后理解层次结构
e、 g“jsonArr”是保存该数据的数组
jsonArr['quotes'][0]['favorite']=true
或者,您可以将其放入for循环中,并遍历此循环到json数组的长度。您可以像这样解析json
Map<String, dynamic> data = jsonDecode(jsonString);
(data["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
(data["quotes"] as List<dynamic>)[position]['favorite'] = true;
添加
是对JSON进行编码和解码的链接,您可以使用以下方法。按下按钮时,字段收藏夹
更改为true
FlatButton(
child: Text('Add Favourite'),
onPressed: (){
myJson['quotes'][myIndex]['favorite'] = true;
})
是的,它将更新字段,然后您可以将数据映射转换为JSON文件是的,您需要将文件中的JSON提取到字符串变量中,然后使用上面的代码进行更新,然后再次将相同的JSON写入相同的文件。我想在JSON文件中进行更改,就像我单击按钮一样,然后特定索引收藏夹的字段更改为true..I需要为每次单击加载整个json文件我想在json文件中更改,就像我单击按钮,然后特定索引收藏夹的文件更改为true。。
FlatButton(
child: Text('Add Favourite'),
onPressed: (){
myJson['quotes'][myIndex]['favorite'] = true;
})