如何在Flutter循环中使用DropdownButton并获取选中值?
你的问题出在selectAttribute的维护方式上:每次选择就往列表里追加元素,但每个Dropdown对应getAttribute的索引,当第二个Dropdown选择时,selectAttribute[index](index=1)会因为列表长度不够抛出越界错误,而且无法正确对应每个Dropdown的选中状态。
修正步骤:
- 初始化选中值列表:获取到
getAttribute后,同步初始化selectAttribute为相同长度的列表,每个元素默认设为null,确保每个Dropdown都有对应的存储位置。 - 修改选中值更新逻辑:在
onChanged中,根据当前Dropdown的索引,直接更新selectAttribute对应位置的值,而不是追加。 - 简化value判断:因为
selectAttribute长度和getAttribute一致,直接使用selectAttribute[index]即可。
修改后的完整代码:
List getAttribute = []; // 初始化时先设为空列表,后续和getAttribute同步长度 List selectAttribute = []; Future getAllAttribuList() async { final attributeList = await deviceAttributeList(context, selectModel); if (attributeList != null) { setState(() { getAttribute = attributeList; // 同步选中值列表长度,每个位置初始为null selectAttribute = List.filled(attributeList.length, null); }); } } List<Widget> getAttrList() { return getAttribute.map((item) { int index = getAttribute.indexOf(item); List options = item.options; return Container( margin: const EdgeInsets.only(bottom: 10.0), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10)), child: DropdownButton( isExpanded: true, // 直接使用对应索引的选中值,null时显示hint value: selectAttribute[index], hint: Text(item.name.toString()), items: options.map((map) { return DropdownMenuItem( child: Text(map.name), value: map.id.toString(), ); }).toList(), onChanged: (value) { setState(() { // 更新对应索引的选中值,而不是追加 selectAttribute[index] = value; }); }, underline: const SizedBox()), ); }).toList(); }
后续使用:
现在selectAttribute列表的每个元素,对应getAttribute中对应位置Dropdown的选中值,比如selectAttribute[0]就是第一个Dropdown的选中ID,直接遍历或按需取值即可。
内容的提问来源于stack exchange,提问作者Berkay Kara
相关产品推荐
相关产品推荐

