当表单滚动到屏幕外时,每个表单字段的状态都会丢失吗?

bak*_*soy 5 flutter

当表单滚动到屏幕外时,如何保存每个表单字段的状态?当我向上滚动并且字段不在屏幕上时,我丢失了在TextFormFields 中输入的值。

我听说过将它保存在控制器中然后分配给 TextFormField 的初始值的建议,如代码所示,但它对我不起作用。我错过了什么?

TextEditingController _controller = new TextEditingController();

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: scaffoldKey,
      appBar: new AppBar(
        title: new Text('Enter Vehicle'),
      ),
      body: new Padding(
          padding: const EdgeInsets.all(16.0),
          child: new Form(
              key: formKey,
              child: new ListView(children: <Widget>[
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Vehicle Number'),
                  controller: _controller,
                  initialValue: _controller.text,
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Tag'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Make'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Model'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Year'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Vehicle Type'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Location'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Fuel'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Other'),
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Your password'),
                  validator: (val) =>
                  val.length < 6 ? 'Password too short.' : null,
                  onSaved: (val) => _password = val,
                  obscureText: true,
                ),
                new RaisedButton(
                  onPressed: _submit,
                  child: new Text('Login'),
                ),
              ],)
          )
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Rai*_*ann 0

您需要TextEditingController为每个字段指定一个专用的属性TextFormField,我认为您不需要initialValue在字段上拥有该属性。

看看这个答案/sf/answers/3166956481/,这也可能有帮助。