Flutter DropdownButton无法从传入列表填充数据求助
让我帮你排查下问题,从你的代码和调试输出来看,数据已经正确传递过来了,问题出在几个小细节上:
1. 下拉按钮被禁用了
你把DropdownButton的onChanged设为了null,这会让整个组件处于不可交互状态——用户根本点不开下拉列表,自然看不到已经生成的选项。你需要给onChanged赋值一个回调函数,用来更新选中的值:
onChanged: (String newValue) { setState(() { itemSel = newValue; }); },
2. DropdownMenuItem显示的是固定文本
你现在的DropdownMenuItem的child是固定的Text("ChildFirstName"),这会导致所有选项都显示同一个字符串,而不是实际的孩子名字。应该改成绑定数据里的ChildFirstName字段:
return new DropdownMenuItem<String>( value: item['ChildId'], child: new Text(item['ChildFirstName']), // 这里改为实际数据字段 );
3. 可选:初始化选中值(如果需要)
如果希望页面加载时默认选中第一个孩子,可以在initState里添加初始化逻辑(注意别忘了调用父类的initState):
@override void initState() { super.initState(); print("OrderInitiate: initstate begin"); print("ChildData: " + widget.childData.toString()); // 如果列表不为空,默认选中第一个孩子 if(widget.childData.isNotEmpty) { setState(() { itemSel = widget.childData[0]['ChildId']; }); } }
修改后的完整DropdownButton代码片段
new DropdownButton<String>( value: itemSel, onChanged: (String newValue) { setState(() { itemSel = newValue; }); }, hint: Text("Select child"), items: widget.childData.map ((item) { print("DropDownButton item: " + item.toString()); print("Child Id: " + item['ChildId']); return new DropdownMenuItem<String>( value: item['ChildId'], child: new Text(item['ChildFirstName']), ); }).toList(), ),
做完这些修改后,下拉按钮应该就能正常展开并显示所有孩子的选项了。
内容的提问来源于stack exchange,提问作者Duncan Pullen
相关产品推荐
相关产品推荐

