Search code examples
flutterdartnullsnapshotdata-mapping

How to map the data from a nested json object in flutter


Here I get this JSON object from the API and I need to add it to a list and return so that I can get it from the snapshot to display the data.But i get the snapshot.data as null.Please help me to solve this issue.

...
{
    "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"
}
...

This is the code on how i tried so far.

...
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,
    );
  }
}
...

From the below code i try to access the data but the snapshot.data get null and the page is loading.

...
    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),
            );
          }
        },
      ),
...

Solution

  • Please update OrderDetails class.

    json['category'] as List is List<dynamic> , not List<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'] == 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');
      }
    }