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

如何在Flutter循环中使用DropdownButton并获取选中值?

动态多DropdownButton选中值获取解决方案

你的问题出在selectAttribute的维护方式上:每次选择就往列表里追加元素,但每个Dropdown对应getAttribute的索引,当第二个Dropdown选择时,selectAttribute[index](index=1)会因为列表长度不够抛出越界错误,而且无法正确对应每个Dropdown的选中状态。

修正步骤:

  1. 初始化选中值列表:获取到getAttribute后,同步初始化selectAttribute为相同长度的列表,每个元素默认设为null,确保每个Dropdown都有对应的存储位置。
  2. 修改选中值更新逻辑:在onChanged中,根据当前Dropdown的索引,直接更新selectAttribute对应位置的值,而不是追加。
  3. 简化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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:50:11