【问题标题】:TextFormField resetting state on focusTextFormField 在焦点上重置状态
【发布时间】:2019-06-10 03:06:15
【问题描述】:

我正在编辑列表中的项目的屏幕。用户点击该项目,我弹出一个新页面打开,其中包含一个 DropdownButton、一个 TextFormField 和一个保存按钮。

如果您先更改 DropdownButton 值,然后点击以聚焦于 TextFormField,则对 DropdownButton 值所做的任何更改都会重置。该值返回到您导航到此页面时设置的初始状态,而不是用户选择的值。如何保留用户在此处选择的值?

为了打开编辑页面,我从正在编辑的列表项中传递参数:

final updated = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => EditPage(
                              display: commute.display,
                              origin: commute.origin)));

EditPage 类本身:

class EditPage extends StatefulWidget {
  String display;
  String origin;

  EditPage({Key key, @required this.display, @required this.origin})
      : super(key: key);

  @override
  EditPageState createState() => EditPageState();
}

class EditPageState extends State<EditPage> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Edit"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            DropdownButton(
              value: widget.origin,
              onChanged: (value) {
                this.setState(() {
                  widget.origin = value;
                });
              },
            ),
            TextFormField(
              initialValue: widget.display,
              onSaved: (value) {
                setState(() {
                  widget.display = value;
                });
              },
            ),
            RaisedButton(
              child: Text('Save'),
              onPressed: () {
                final form = _formKey.currentState;
                if (form.validate()) {
                  form.save();
                  final thing =
                      Thing(display: widget.display, origin: widget.origin);
                  Navigator.pop(context, thing);
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 我认为你需要为每个 TextFormField 设置 TextEditingController 来保存文本字段的状态

标签: flutter


【解决方案1】:

问题最终是Navigator。损坏的代码会推送EditPage 的新副本,而不是固定版本。将代码更改为此就可以了:

final editor = EditPage(
                 display: commute.display,
                 origin: commute.origin);

final updated = await Navigator.push(context,
                      MaterialPageRoute(builder: (context) => editor));

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 2021-08-25
    • 2020-06-18
    • 2021-06-25
    • 2020-02-02
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多