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

Flutter中Firestore数据填充的Dropdown选中值不更新问题求助

解决Dropdown选中值不更新的问题

你的问题出在selectedValue的定义位置——它被放在了StreamBuilder的builder函数内部。每次StreamBuilder重建(比如Firestore数据更新、调用setState时),这个变量都会被重新初始化为null,所以你点击选项后看似更新了值,但下次重建又回到初始状态,导致Dropdown的选中提示文本不变。

修复方案:

把selectedValue改成组件类的成员变量,放在build方法外面,这样它的状态能在组件生命周期内保留:

// 将selectedValue提升为组件类的成员变量
String? selectedValue;

@override
Widget build(BuildContext context) {
  return StreamBuilder<QuerySnapshot>(
    stream: compDoc.snapshots(),
    builder: (context, snapshot) {
      if (snapshot.hasError) {
        return Center(child: Text("Some error occurred ${snapshot.error}"),);
      }
      List<DropdownMenuItem> compItems = [];
      if (!snapshot.hasData) {
        return const CircularProgressIndicator();
      } else {
        final selectComp = snapshot.data?.docs.toList();
        if (selectComp != null) {
          for (var comp in selectComp) {
            compItems.add(
              DropdownMenuItem(
                value: comp['name'],
                child: Text(
                  comp['name'],
                ),
              ),
            );
          }
        }
        return Padding(
          padding: const EdgeInsets.all(10.0),
          child: Container(
            padding: const EdgeInsets.only(right: 15, left: 15),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey, width: 1),
              borderRadius: BorderRadius.circular(15),
            ),
            child: DropdownButton(
              underline: const SizedBox(),
              isExpanded: true,
              hint: Text(
                "Select items",
                style: TextStyle(fontSize: 20),
              ),
              value: selectedValue,
              items: compItems,
              onChanged: (value) {
                setState(() {
                  selectedValue = value;
                  print(selectedValue);
                });
              },
            ),
          ),
        );
      }
    },
  );
}

这样修改后,选中的值会被持久化在成员变量里,setState触发重建时,selectedValue不会被重置,Dropdown就能正确显示选中的选项了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:57:08