You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问Dart中List<Map<String, Object>>的双层嵌套集合?

嵌套集合访问方法与代码示例

一、核心问题解决

针对你提供的List<Map<String, Object>>结构,以下是具体的访问方法:

1. 获取ingredients列表中的项

recipes[1]['ingredients']返回的是一个列表,通过列表索引可直接访问元素,也可以遍历所有元素:

// 获取第二个食谱的第一个食材
print(recipes[1]['ingredients'][0]); // 输出: cucumber
// 遍历第二个食谱的所有食材
for (var ingredient in recipes[1]['ingredients']) {
  print(ingredient);
}

2. 获取macros映射中的protein值

recipes[1]['macros']返回的是嵌套Map,直接通过键名'protein'访问对应值:

// 获取第二个食谱的蛋白质含量
print(recipes[1]['macros']['protein']); // 输出: 17.1

3. 获取macros的长度

嵌套Map的长度可通过.length属性直接获取:

// 获取第二个食谱macros的键值对数量
print(recipes[1]['macros'].length); // 输出: 7

二、完整示例代码

整合上述方法的代码如下:

void main() {
  var recipes = [
    {
      'name': 'Hoisin Chicken Lettuce Cups',
      'type': 'Salad',
      'ingredients': ['mango', 'hoisin sauce', 'chicken breasts', 'romaine lettuce', 'cress'],
      'calories': 289,
      'macros': {
          'fat': 9.6,
          'sat_fat': 1.8,
          'protein': 31.3,
          'carbs': 20.3,
          'sugar': 19.2,
          'salt': 1.3,
          'fibre': 2.5,
        },
    },
    {
      'name': 'Smoked Salmon Plates',
      'type': 'Salad',
      'ingredients': ['cucumber', 'dill', 'smoked salmon', 'avocado', 'cottage cheese'],
      'calories': 246,
      'macros': {
          'fat': 17.7,
          'sat_fat': 3.9,
          'protein': 17.1,
          'carbs': 4.4,
          'sugar': 3.2,
          'salt': 1.5,
          'fibre': 1.2,
        },
    },
  ];

  // 访问ingredients列表项
  print("第二个食谱的第一个食材:${recipes[1]['ingredients'][0]}");
  print("第二个食谱的所有食材:");
  for (var ing in recipes[1]['ingredients']) {
    print("- $ing");
  }

  // 访问macros中的protein值
  print("第二个食谱的蛋白质含量:${recipes[1]['macros']['protein']}");

  // 获取macros的长度
  print("第二个食谱macros的键值对数量:${recipes[1]['macros'].length}");

  // 遍历第一个食谱的所有macros数据
  print("第一个食谱的营养成分:");
  var firstMacros = recipes[0]['macros'] as Map;
  firstMacros.forEach((key, value) {
    print("- $key: $value");
  });
}

三、学习建议

  1. 先从Dart基础集合(List、Map)的单独使用练起,熟练掌握单一层级的访问、遍历、修改操作,再过渡到嵌套结构。
  2. 练习时先写简单的嵌套示例(比如List<List<int>>、Map<String, List<String>>),逐步增加复杂度,不要一开始就碰多层嵌套的复杂结构。
  3. 利用Dart的类型转换(比如as Map/as List)让编辑器给出更精准的代码提示,减少出错概率。

内容的提问来源于stack exchange,提问作者ZgroNet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:24:31