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

Flutter中DropdownButton2选中项后控制器未实时更新问题求助

解决DropdownButton2选中选项后UI不实时更新的问题

问题分析

选中选项后selectedFermentable已更新,但DropdownButton2的显示文本未实时刷新,仅在保存代码后才更新,核心原因是组件未正确感知状态变化,无法触发即时重建。

修复方案

1. 绑定选中值作为组件唯一Key

给DropdownButton2添加与selectedFermentable绑定的ValueKey,强制组件在选中值变化时触发重建:

DropdownButton2(
  key: ValueKey(selectedFermentable), // 添加此行
  isExpanded: true,
  // 其他原有属性保持不变
)

2. 优化类型赋值逻辑

避免强制类型转换的潜在风险,将selectedFermentable声明为String?类型,并在onChanged中安全赋值:

// 类成员变量声明
String? selectedFermentable;

// 修改onChanged回调
onChanged: (value) {
  setState(() {
    selectedFermentable = value; // 直接赋值,去掉强转
  });
},

3. 统一搜索匹配逻辑

确保搜索匹配逻辑与选项值的处理完全一致,避免大小写或格式差异导致的匹配异常:

searchMatchFn: (item, searchValue) {
  return item.value?.toLowerCase().contains(searchValue.toLowerCase()) ?? false;
},

完整修正代码

DropdownButtonHideUnderline(
  child: DropdownButton2(
    key: ValueKey(selectedFermentable), // 添加唯一Key
    isExpanded: true,
    hint: Text(
      'Selecione um fermentável',
      style: textTheme.bodyMedium,
    ),
    items: fermentables
        .map((item) => DropdownMenuItem<String>(
              value: item.name.toLowerCase(),
              child: Text(
                item.name,
                style: const TextStyle(
                  fontSize: 14,
                ),
              ),
            ))
        .toList(),
    value: selectedFermentable,
    onChanged: (value) {
      setState(() {
        selectedFermentable = value; // 安全赋值
      });
    },
    buttonHeight: 40,
    buttonWidth: 200,
    itemHeight: 40,
    dropdownMaxHeight: 400,
    searchController: fermentableName,
    searchInnerWidgetHeight: 50,
    searchInnerWidget: Container(
      height: 50,
      padding: const EdgeInsets.only(
        top: 8,
        bottom: 4,
        right: 8,
        left: 8,
      ),
      child: TextFormField(
        expands: true,
        maxLines: null,
        controller: fermentableName,
        decoration: InputDecoration(
          isDense: true,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 10,
            vertical: 8,
          ),
          hintText: 'Pesquise um fermentável',
          hintStyle: textTheme.bodyMedium,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      ),
    ),
    searchMatchFn: (item, searchValue) {
      return item.value?.toLowerCase().contains(searchValue.toLowerCase()) ?? false;
    },
    onMenuStateChange: (isOpen) {
      if (!isOpen) {
        fermentableName.clear();
      }
    },
  ),
),

内容的提问来源于stack exchange,提问作者trovap

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:52:37