Iterate through map data within a nested sub-map

Viewed 178

Our app receives nested JSON data from Firebase. We store this data in List of Object Item & Object Order.

Object Order can have multiple attributes, int price; List item; itemDecription. Sublist item can have multiple strings of itemName.

When we attempt to access itemName, in rasterMap, it is only accessing the last item in the list. How can we access multiple all values of itemName in rasterMap?

Our data structure is:


{
    "Orders": {
        "-MPuETb4vq2NdtQl-_y1": {
            "name": "Pulled Pork Sandwich",
            "price": 14.00

        },
        "-fbdhfunshy-_y2": {
            "name": "BBQ Spare Ribs",
            "price": 14.00

        }
    }
}
----Begin code---

//List to create orderItem with object item
    List<Item> orderItems = []; 
//List to create orderList with object item
    List<Order> orderList = [];


//Retrieve JSON
//Firebase connection here
 if (!_checkIfObjectExist(orderDate)) {
    Item itemObj = Item.fromJson(event.documents[i].data);
        orderItems.add(itemObj);
    Order orderObj = Order.fromJson(event.documents[i].data);

}
//iterate through order list 
  for (int i = 0; i < orderList.length; i++ ) {
      print(orderList);
      for(int j = 0; j < orderList[i].item.length; j++) {
        itemName = orderList[i].item[j].itemName;
        print(itemName);
      }
  }

Map<String, dynamic> rasterMap = {
          'appendBitmapText':
        "LIST ITEM NAMES IN THIS STRING MAP HERE"
        };
1 Answers
import 'dart:convert';

// your current structure
const rawData = '''
{
  "Orders": {
    "-MPuETb4vq2NdtQl-_y1": {
      "name": "Pulled Pork Sandwich",
      "price": 14.00
    },
    "-fbdhfunshy-_y2": {
      "name": "BBQ Spare Ribs",
      "price": 14.00
    }
  }
}
''';

// My suggestion for your structure
const rawData2 = '''
{
  "Orders": [
    {
      "id": "-MPuETb4vq2NdtQl-_y1",
      "name": "Pulled Pork Sandwich",
      "price": 14.00
    },
    {
      "id": "-fbdhfunshy-_y2",
      "name": "BBQ Spare Ribs",
      "price": 14.00
    }
  ]
}
''';


class Order {
  String? id, name;
  double? price;

  Order.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    price = json['price'];
  }
}


void main(List<String> args) {
  final data = jsonDecode(rawData2)['Orders'] as List;
  var orders = <Order>[];
  
  data.forEach((m) => orders.add(Order.fromJson(m as Map<String, dynamic>)));
  print(orders);
}

Result:

[Instance of 'Order', Instance of 'Order']
Related