如何使用嵌套循环从 flutter 中的 rest api 中获取数据?

How to use nested loops for fetching the data from a rest api in flutter?

我有一个订单屏幕,其中显示已下订单和为每个订单下的商品。我使用 for 循环从 api 获取订单,但在订单 json 响应中它也有 items 参数,其中有多个项目。我无法弄清楚如何在代码中放置另一个循环来获取项目列表。所以请帮帮我... 谢谢..

我的json回复

    [
    {
    "id": 1453,
    "total": "407.00",
    "line_items": [
        {
            "id": 34,
            "name": "Aloo Chaat Salad",
            "product_id": 931,
            "quantity": 1,
            "total": "90.00",
        },
        {
            "id": 35,
            "name": "Aloo Jeera",
            "product_id": 1020,
            "quantity": 1,
            "total": "140.00",
        },
        {
            "id": 36,
            "name": "Banana Shake",
            "product_id": 963,
            "quantity": 1,
            "tax_class": "",
            "total": "140.00",
        }
    ],
  }
] 

myModel.dart

class OrderListModel {
final int id;
final String total;

 Map line_items = {};

  OrderListModel(this.id, this.total, this.line_items);

 }

我获取数据的代码

 List<OrderListModel> myAllDatas = [];

Future getDatas() async {
String basicAuth = 'Basic ' +
    base64.encode(
        utf8.encode('${GlobalVar.consumerKey}:${GlobalVar.secretKey}'));

var response = await http
    .get("${GlobalVar.url}wp-json/wc/v2/orders?customer=6", headers: {
  'Authorization': basicAuth,
  'Accept': 'application/json',
});
if (response.statusCode == 200) {
  String responseBody = response.body;
  var jsonBody = json.decode(responseBody);
  for (var data in jsonBody) // loop for fetching the orders
  {
    myAllDatas.add(new OrderListModel(data['id'], data['total'], 
data['line_items'])); // how to place a loop so that i can fetch the items 
inside the line_items parameter too?
  }
  setState(() {});
} else {
  print(response.statusCode);
  print(response.body);
}
}

当我获取 line_items 的项目时,我只想获取它们的名称并用逗号分隔成一行。

像这样使用 for 循环 -

for (var data in body) {
    List items = data["line_items"];
    for (int i = 0; i < items.length; i++) {
      int id = items[i]["id"];
      String name = items[i]["name"];
    }
  }