Flutter的DropDownButton无DropDownMenuItems选项如何修复?
问题原因
- 接口返回的JSON为两层嵌套数组结构
[[...]],直接将根数组赋值给产品列表变量,实际拿到的数据结构和预期不符,无法正确读取产品字段 - 接口请求拿到数据后没有调用
setState通知Flutter刷新UI,即使数据正确页面也不会更新 - 初始选中值
_mySelection默认是空字符串,和下拉选项的value值范围不匹配,会导致组件渲染异常 - JSON解析后的dynamic类型没有做手动转换,直接强转可能抛出类型异常
- 需确认已经在State的
initState生命周期中调用了请求方法发起接口调用
修复代码
1. 变量定义调整
List<Map<String, String>> customerData = []; // 初始值设为可空类型,适配hint显示逻辑 String? _mySelection;
2. 接口请求逻辑修复
Future<void> getCustomerData() async { var res = await http.get(Uri.parse('http://172.30.1.6/product.php')); var resBody = json.decode(res.body); // 取外层数组第一个元素,得到真实的产品列表 List productList = resBody[0]; // 手动遍历转换类型,避免强转异常 List<Map<String, String>> _mapCustomer = productList.map((item) { return Map<String, String>.from(item); }).toList(); // 调用setState更新数据,触发UI重绘 setState(() { customerData = _mapCustomer; // 可选配置:默认选中第一个产品 if (customerData.isNotEmpty) { _mySelection = customerData.first['ProductName']; } }); }
3. 新增initState生命周期调用请求
@override void initState() { super.initState(); // 页面初始化时发起接口请求 getCustomerData(); }
4. DropdownButton组件适配
Container( height: 70.0, padding: EdgeInsets.all(10), child: DropdownButton<String>( value: _mySelection, // 数据为空时显示加载中提示,避免组件报错 items: customerData.isEmpty ? [ DropdownMenuItem(value: null, child: Text('加载中...')) ] : customerData.map((Map<String, String> product) { return DropdownMenuItem( value: product["ProductName"], child: Text(product["ProductName"]!) ); }).toList(), onChanged: (newValue) { setState(() { _mySelection = newValue!; }); }, hint: Text('ProductName'), ) )
优化建议
如果可以修改PHP接口,建议直接去掉外层嵌套的数组,返回结构如下,后续解析不需要额外取[0],结构更规范:
[{"ProductID":"3","ProductName":"test"},{"ProductID":"4","ProductName":"test1"}]
内容的提问来源于stack exchange,提问作者Malone
相关产品推荐
相关产品推荐

