【问题标题】:How to map the data from a nested json object in flutter如何在flutter中映射嵌套json对象中的数据
【发布时间】:2021-07-29 11:18:32
【问题描述】:

在这里,我从 API 获取这个 JSON 对象,我需要将它添加到列表并返回,以便我可以从快照中获取它以显示数据。但是我将 snapshot.data 获取为 null。请帮助我来解决这个问题。

...
{
    "Data": [
        {
            "product_name": "MACC Tea Master Blend 40 Bags",
            "img_url": "1605262901.jpg",
            "order_no": "1625809545122",
            "category": [
                {
                    "category_name": "01 Box (40 Bags)",
                    "order_no": "1625809545122",
                    "qty": "1",
                    "line_total": "1.79"
                }
            ]
        }
    ],
    "ID": "200"
}
...

这是我目前尝试的代码。

...
Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
  var body = jsonEncode({"order_no": order_no});
  print("order_no : " + order_no);
  http.Response response = await http.post(
      Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
      headers: {"Accept": "application/json"},
      body: body);
  if (response.statusCode == 200) {
    Map<String, dynamic> map = json.decode(response.body);
    // var map = json.decode(response.body);
    print("response.body : " + "${response.body}");
    print("map : " + "${map['Data']}");

    List<OrderDetails> orderDetailsList;
    orderDetailsList = (json.decode(response.body)['Data'] as List)
        .map((i) => OrderDetails.fromJson(i))
        .toList();

    return orderDetailsList;
  } else {
    // print("Failed to load categories");
    throw Exception('Failed to load the Orders');
  }
}

class OrderDetails {
  final String product_name;
  final String img_url;
  final String order_no;
  final List<Category> category;

  OrderDetails({
    this.product_name,
    this.img_url,
    this.order_no,
    this.category,
  });

  factory OrderDetails.fromJson(Map<String, dynamic> json) {
    return OrderDetails(
      product_name: json['product_name'] as String,
      img_url: json['img_url'] as String,
      order_no: json['order_no'] as String,
      category: json['category'] as List,
    );
  }
}

class Category {
  final String category_name;
  final String qty;
  final String line_total;

  Category({this.category_name, this.qty, this.line_total});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      category_name: json['category_name'] as String,
      qty: json['qty'] as String,
      line_total: json['line_total'] as String,
    );
  }
}
...

从下面的代码中,我尝试访问数据,但 snapshot.data 为空并且页面正在加载。

...
    child: FutureBuilder<List<OrderDetails>>(
        future: fetchMyOrderDetails(order_no),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          print("snapshot data : " + "${snapshot.data}");
          if (snapshot.data == null) {
            return Container(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else {
            return Center(
              child: Text(snapshot.data.product_name),
            );
          }
        },
      ),
...

【问题讨论】:

    标签: flutter dart null snapshot data-mapping


    【解决方案1】:

    请更新OrderDetails类。

    json['category'] as ListList&lt;dynamic&gt; ,而不是 List&lt;Category&gt;

    factory OrderDetails.fromJson(Map<String, dynamic> json) {
        return OrderDetails(
          product_name: json['product_name'] as String,
          img_url: json['img_url'] as String,
          order_no: json['order_no'] as String,
          category: (json['category'] == null) 
                        ? null 
                        : (json['category'] as List).map(e => Category.fromJson(e)).toList(),
        );
    }
    
    
    Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
      var body = jsonEncode({"order_no": order_no});
      print("order_no : " + order_no);
      http.Response response = await http.post(
          Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
          headers: {"Accept": "application/json"},
          body: body);
      if (response.statusCode == 200) {
        Map<String, dynamic> map = json.decode(response.body);        
        print("response.body : " + "${response.body}");
        print("map : " + "${map['Data']}");
    
        List<OrderDetails> orderDetailsList;
        orderDetailsList = (map['Data'] as List)
            .map((i) => OrderDetails.fromJson(i))
            .toList();
    
        return orderDetailsList;
      } else {
        // print("Failed to load categories");
        throw Exception('Failed to load the Orders');
      }
    }
    

    【讨论】:

    • ════════ 小部件库捕获的异常═══════════════════════════ ══════════════════════════类“List”没有实例获取器“product_name”。接收方:“_GrowableList”的实例(长度:1)尝试调用:product_name
    猜你喜欢
    • 2021-06-20
    • 2021-10-10
    • 2021-03-29
    • 2020-02-19
    • 2021-12-11
    • 2019-09-15
    • 2018-01-10
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多