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

Flutter:提交表单时如何将DropdownMenu选中值保存到FireStore

问题分析

你的代码逻辑其实已经走对了大半:DropdownMenu能从FireStore拉取数据,选中值也通过setState更新到了chosenPlatform变量里。但提交按钮的FireStore写入代码里,完全没把chosenPlatform这个变量包含进去,这就是平台值没保存的核心原因!

修复步骤

1. 确保chosenPlatform变量正确初始化

首先确认你的State类里已经定义了这个变量(如果还没的话),建议给个初始值或者允许为空:

class YourWidgetState extends State<YourWidget> {
  String chosenPlatform; // 或者 String chosenPlatform = ""; 根据需求调整
  // 其他控制器变量...
  TextEditingController tourneynameController = TextEditingController();
  TextEditingController tourneydateController = TextEditingController();
}

2. 修改提交按钮的FireStore写入逻辑

在add()方法的Map参数里,新增一行'platform': chosenPlatform,把选中的平台值一起提交:

RaisedButton(
  padding: EdgeInsets.only(left: 10, right: 10),
  onPressed: () async {
    // 可选:添加校验,确保用户已经选择了平台
    if (chosenPlatform == null) {
      Scaffold.of(context).showSnackBar(
        SnackBar(content: Text("请先选择比赛平台!")),
      );
      return;
    }

    await Firestore.instance.runTransaction((Transaction transaction) async {
      final CollectionReference reference = Firestore.instance
          .collection('Tournaments');
      await reference
          .document('Fifa Tournaments')
          .collection('Fifa Tourneys')
          .add({
        'tourneyname': tourneynameController.text,
        'tourneygame': tourneydateController.text,
        'platform': chosenPlatform, // 新增这一行!
      });
      tourneynameController.clear();
      tourneydateController.clear();
      // 可选:清空选中的平台值
      setState(() {
        chosenPlatform = null;
      });
    });
    Navigator.of(context).pop();
  },
  // 其他按钮属性保持不变...
)

3. 修复StreamBuilder的小问题

你的Dropdown代码里,当snapshot.hasData为false时,没有用return返回加载组件,这会导致后续代码继续执行引发错误,修正一下:

builder: (context, snapshot) {
  if (!snapshot.hasData) return const Text("Loading....."); // 加上return
  else {
    // 原来的Dropdown逻辑...
  }
}

验证效果

现在重新运行代码,选择平台后点击提交,就能在Tournaments/Fifa Tournaments/Fifa Tourneys集合里看到包含platform字段的新文档了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:42:33