Flutter/Dart中如何从下拉列表获取选中项的指定字段值
解决Flutter下拉菜单选中后打印指定字段的问题
嘿,这个需求很好实现,我给你两种可行的方案,你可以根据自己的习惯选一种:
方案一:通过选中的ID查找对应的用户对象
你的现有代码里userId存储的是选中用户的ID,那我们只需要在onChanged回调里,根据这个ID从users列表中找到对应的用户,然后取出designation字段打印就好啦。
修改后的onChanged代码如下:
onChanged: (String? newValue) { setState(() { userId = newValue; }); // 查找选中的用户对象 if (newValue != null) { final selectedUser = users.firstWhere( (user) => user['id'] == newValue, orElse: () => {}, ); // 打印职位,如果找到用户的话 if (selectedUser.isNotEmpty) { print(selectedUser['designation']); } } },
方案二:直接存储选中的用户对象(更简洁)
其实我们可以不用存ID,直接把整个用户对象作为DropdownMenuItem的value,这样选中时直接拿到完整的用户信息,不用再去列表里查找,代码会更简洁。
修改后的完整代码如下:
import 'package:flutter/material.dart'; class TestPage extends StatefulWidget { const TestPage({Key? key}) : super(key: key); @override State<TestPage> createState() => _TestPageState(); } class _TestPageState extends State<TestPage> { List users = [ { 'id': '1', 'name': 'roy', 'designation': 'engineer', }, { 'id': '2', 'name': 'john', 'designation': 'doctor', }, { 'id': '3', 'name': 'rose', 'designation': 'clerk', } ]; // 改为存储用户对象,而不是ID Map<String, dynamic>? selectedUser; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: DropdownButtonHideUnderline( child: DropdownButton<Map<String, dynamic>>( isExpanded: true, hint: const Padding( padding: EdgeInsets.all(8.0), child: Text('Select Item'), ), value: selectedUser, items: users.map((item) { return DropdownMenuItem( child: Text(item['name']), // value直接设为整个用户对象 value: item, ); }).toList(), onChanged: (Map<String, dynamic>? newValue) { setState(() { selectedUser = newValue; }); // 直接打印职位 if (newValue != null) { print(newValue['designation']); } }, ), ), ), ); } }
两种方案都能实现你的需求,方案二更直观,减少了一次查找操作,推荐使用哦~
内容的提问来源于stack exchange,提问作者MURALI KRISHNAN MT
相关产品推荐
相关产品推荐

