繁体   English   中英

如何在flutter中更新本地json字段

[英]How to update the local json field in flutter

我是 flutter 和 dart 的新手我阅读了很多网络文章和文档,但无法弄清楚如何更新 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 sometimes your smile can be the source of your joy.",
  "favorite":false
  }]}

我想在 JSON 文件中将归档的收藏更新为 true 有没有办法做到这一点

您可以在JSON中的quotes列表上使用forEach循环,并将其中的favourite设置为true 我假设您已经使用jsonDecodejson.decodeString数据解析为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;
});

您也可以为forEach循环功能使用简写语法,如下所示-

(jsonData["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);

首先将此json数组带到任何变量,然后了解层次结构。

例如,“ 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);

如果您想将单个对象的值设置为true则需要像这样传递position

(data["quotes"] as List<dynamic>)[position]['favorite'] = true;

加成

是编码和解码JSON的链接

您可以使用以下方法。 当按下按钮时,字段favorite将更改为true

FlatButton(
    child: Text('Add Favourite'),
    onPressed: (){
         myJson['quotes'][myIndex]['favorite'] = true;
})

如果您使用JSON模型并将其声明为可变模型,则可以直接在源数据上执行此修改。

import 'dart:convert';

import 'json_objects.dart';

void main() {
  var json = jsonDecode(_source) as Map<String, dynamic>;
  var response = Response1.fromJson(json);
  for (var quote in response.quotes) {
    quote.favorite = false;
  }

  json = response.toJson();
  print(json);
}

final _source = r'''
{
    "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
        }
    ]
}''';

结果:

{category: Happiness, quotes: [{favorite: false, 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.}]}

使用的JSON模型。

class Response1 {
  String category;
  List<Response1Quotes> quotes;

  Response1({this.category, this.quotes});

  factory Response1.fromJson(Map<String, dynamic> json) {
    return Response1(
      category: json['category'] as String,
      quotes: _toObjectList(json['quotes'], (e) => Response1Quotes.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'category': category,
      'quotes': _fromList(quotes, (e) => e.toJson()),
    };
  }
}

class Response1Quotes {
  bool favorite;
  String quote;

  Response1Quotes({this.favorite, this.quote});

  factory Response1Quotes.fromJson(Map<String, dynamic> json) {
    return Response1Quotes(
      favorite: json['favorite'] as bool,
      quote: json['quote'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'favorite': favorite,
      'quote': quote,
    };
  }
}

List _fromList(data, Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = [];
  for (var element in data) {
    var value;
    if (element != null) {
      value = toJson(element);
    }
    result.add(value);
  }
  return result;
}

List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <T>[];
  for (var element in data) {
    T value;
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result.add(value);
  }
  return result;
}

/*
Response1:
  "category": String
  "quotes": List<Response1Quotes>

Response1Quotes:
  "quote": String
  "favorite": bool
*/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM