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

Flutter中如何将TextFormField的hintText值存储到Firebase数据库?

问题原因

TextFormField的onSaved回调返回的仅为用户输入的组件value值,你将从上一页传递过来的机构名称存到了hintText这个装饰属性中,同时该字段设置了readOnly: true无用户输入操作,组件的value默认始终为空,因此onSaved赋值给facName的结果自然为空,导致Firebase中存储的字段无值。

解决方案

提供两种可直接落地的修改方式:

方案1:给只读表单字段设置初始值

给getFacilityName组件添加initialValue属性,让表单默认值等于传递过来的机构名称,onSaved即可正常捕获到值:

Widget getFacilityName() => TextFormField(
   readOnly: true,
   initialValue: widget.facilityName, // 新增这一行
    decoration: InputDecoration(
      labelText: 'Hospital / Clinic Name',
      floatingLabelBehavior: FloatingLabelBehavior.always,
      hintText: widget.facilityName,
      border: OutlineInputBorder(),
      suffixIcon: Icon(Icons.local_hospital),
    ),
    onSaved: (value) => setState(() => facName = value),
  );

如果不需要显示hint提示,也可以删除hintText配置,不影响功能。

方案2:提交时直接使用传递过来的参数

你已经从上一页拿到了widget.facilityName参数,可以跳过表单取值步骤,提交时直接使用该值即可:
找到提交逻辑里的写入代码,修改facilityName的取值来源:

await reference.add({
  "facilityName": widget.facilityName, // 直接用传过来的参数,不需要用facName变量
  "name": "$name", 
  "ic": "$ic", 
  "phoneno": "$phoneNo", 
  "datetime": "$date"
});

这个方案无需修改getFacilityName组件的现有配置,实现更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:39:02