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

如何从Flutter的DropdownButton组件同时获取ID和Name两个返回值

实现方案

你现在只拿到StudentID是因为DropdownMenuItem的value属性仅绑定了ID值,要同时获取两个字段可以用以下两种方式修改:


方案1:直接绑定完整学生对象(推荐)

修改点:

  • 调整_StudentSelection变量类型,从原有的String类型改为存储Map类型的完整学生数据,初始化时直接赋值默认选中的完整对象:
    // 初始化示例,Amy对应StudentData的第一个元素
    var _StudentSelection = StudentData[0];
    
  • 修改DropdownButton的泛型、item的value绑定、onChanged逻辑:
    Row(
      children: <Widget>[Container(
          padding: EdgeInsets.only(left:5),
          // 指定泛型为Map,和value类型对应
          child: DropdownButton<Map>(
            value: _StudentSelection,
            items: StudentData.map((product) {
              return DropdownMenuItem(
                  // value绑定完整的学生Map对象
                  value: product,
                  child: Text(product["StudentName"]!)
              );
            }).toList(),
            onChanged: (Map? newValue) {
              setState(() {
                _StudentSelection = newValue!;
                // 此时直接从_StudentSelection取值即可
                debugPrint("选中的ID:${_StudentSelection["StudentID"]}");
                debugPrint("选中的姓名:${_StudentSelection["StudentName"]}");
              });
            },
            hint: Text('StudentID'),
          )
      ),
      ],
    )
    

方案2:保留原有ID存储逻辑,选中后匹配数组

如果不想修改_StudentSelection原有的String类型,可以在选中时通过ID遍历StudentData获取对应姓名:

Row(
  children: <Widget>[Container(
      padding: EdgeInsets.only(left:5),
      child: DropdownButton(
        value: _StudentSelection,
        items: StudentData.map((product) {
          return DropdownMenuItem(
              value: product["StudentID"].toString(),
              child: Text(product["StudentName"]!)
          );
        }).toList(),
        onChanged: (String? newValue) {
          setState(() {
            _StudentSelection = newValue!;
            // 通过ID匹配获取对应完整学生数据
            var selectedStudent = StudentData.firstWhere((item) => item["StudentID"] == newValue);
            String selectedName = selectedStudent["StudentName"];
            debugPrint("选中的ID:$_StudentSelection,选中的姓名:$selectedName");
          });
        },
        hint: Text('StudentID'),
      )
  ),
  ],
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:06:03