setState() 清除表单元素数据flutter中的数据

setState() clears the data in form element data flutter

我刚开始使用 Sateful 小部件进行 flutter 和试验。事情是这样的,在我的 UI 屏幕布局中,我有两个不同的小部件

  1. DropdownButton 小部件
  2. 保存卡号的TextFormField。

当我尝试将下拉选择的值更新到 DropdownButton 小部件时,它会自动清除 TextFormField 中的文本。每次调用setState()方法更新值时,是否需要在全局变量中存储文本才能重新恢复?

这是小部件的代码, 下拉按钮

 new Padding(
              padding: const EdgeInsets.all(15.0),
              child: new Column(
                children: <Widget>[
                  DropdownButton<String>(
                    value: _referPractice,
                    isDense: true,
                    hint: new Text(CONST_SELECT),
                    items: _stdCodesList.map((value) {
                      return new DropdownMenuItem<String>(
                        value: value.dialCode,
                        child: new Text("${value.code} ${value.dialCode}"),
                      );
                    }).toList(),
                    onChanged: (String newValue) {
                      setState(() {
                        _referPractice = newValue;  // here I`m trying to update selected value. 
                      });
                    },
                  )
                ],
              )),

TextFormField

TextFormField(
                controller: _textController,
                keyboardType: TextInputType.number,
                style: new TextStyle(
                  fontWeight: FontWeight.w200,
                  color: Colors.black,
                  fontSize: 18.0,
                ),
                decoration: new InputDecoration(
                    hintText: HING_ENTER_NUMBER,
                    suffixIcon: CircleIconButton(
                      onPressed: () {
                        this.setState(() {
                          _textController.clear();
                        });
                      },
                    )),
                maxLines: 1,
                validator: (value) {
                  if (value.isEmpty) {
                    return ERROR_CARD_DETAILS;
                  }
                },
              ),

我知道有状态小部件每次调用 setState 时都会重建小部件,但我如何保留尚未存储在任何地方的表单数据的数据。

请多多指教!提前致谢。

对于给定的代码,我能想到的一个错误是每次都创建 TextEditingController

@override
Widget build(BuildContext context) {
  var _textController = TextEditingController(); //problem
  // build and return widgets

应该在build方法的外面。我们可以在 constructorinitState.

中使用它

如果 build 之外还有 _textController,你能再添加一些代码吗?