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

Flutter中DropdownButton从Firebase取初始值后无法修改的问题

问题根因

你在build方法中直接对下拉框绑定值governorateDDValue赋值Firebase存储的原始值,而每次手动选择下拉项触发setState时,都会重新执行build方法,你刚修改的选中值会立刻被原始值覆盖,因此出现无法手动修改的问题。

修复方案

只要保证初始值仅在页面首次加载时赋值1次,后续build不再覆盖即可,参考修改代码如下:

class _UserInfoState extends State<UserInfo> {
  late User selectedUser;
  final date = DateFormat('yyyy-MM-dd').format(DateTime.now()).toString();
  var governorateDDValue;
  // 新增首次加载标记
  bool _isFirstLoad = true;

  @override
  Widget build(BuildContext context) {
    final userList= Provider.of<List<User>>(context);
    final userID = ModalRoute.of(context)!.settings.arguments as String;
    selectedUser = userList.firstWhere((user) => user.id == userID);

    // 仅首次加载时赋值Firebase初始值,后续不再执行
    if (_isFirstLoad) {
      governorateDDValue = selectedUser.governorate;
      _isFirstLoad = false;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('report'),
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Row(
            children: <Widget>[
              const Text('Governorate'),
              Container(height: 5),
              DropdownButton<String>(
                value: governorateDDValue,
                icon: const Icon(Icons.arrow_downward),
                iconSize: 24,
                elevation: 16,
                style: const TextStyle(color: Colors.deepPurple),
                onChanged: (String? newValue) {
                  setState(() {
                    governorateDDValue = newValue!;
                  });
                },
                items: Constants.governoratesOfEgypt
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

如果你的业务场景需要支持userList数据更新后同步刷新下拉初始值,可以额外加判断逻辑,当selectedUser的唯一标识发生变化时重置_isFirstLoad为true即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:45:00