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

Flutter中如何将Map值添加到List?新手技术求助

在Flutter中创建包含指定Map的List

1. 直接初始化List并添加Map数据

你可以直接定义一个泛型为Map<String, String>的List,把目标Map数据放入其中:

// 定义存储学生考勤数据的List
List<Map<String, String>> studentAttendance = [
  {
    'studAttId': 'null',
    'divisionId': '4365eb0b-fb48-42f9-be4e-e9c1c695aeab',
    'id': 'e49d6d0d-0036-417c-a0ff-330e51cb947d',
    'forenoon': 'P',
    'afternoon': 'P',
    'admNo': '496',
    'rollNo': 'null',
    'name': 'A M MUHAMMED AFSAL',
    'terminatedStatus': 'null'
  },
  // 此处可继续添加更多同格式的Map元素
];

2. 动态添加新的Map数据

如果需要后续往List中追加数据,使用add()方法即可:

// 新增一条学生考勤记录
studentAttendance.add({
  'studAttId': '123',
  'divisionId': 'new-division-id',
  'id': 'new-student-id',
  'forenoon': 'A',
  'afternoon': 'P',
  'admNo': '497',
  'rollNo': '5',
  'name': 'John Doe',
  'terminatedStatus': 'null'
});

3. 访问List中的数据

要获取List内的具体内容,通过索引+键名即可:

// 获取第一个学生的姓名
String studentName = studentAttendance[0]['name'] ?? '';
// 获取第一个学生的上午考勤状态
String forenoonStatus = studentAttendance[0]['forenoon'] ?? '';

print(studentName); // 输出: A M MUHAMMED AFSAL
print(forenoonStatus); // 输出: P

注:使用?? ''是为了避免键不存在时返回null引发报错,让代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:15:35