首页 文章

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

提问于
浏览
1

我是新手,可以用Sateful小部件进行实验 . 这是事情,在我的UI屏幕布局中,我有两个不同的小部件

  • DropdownButton小部件

  • TextFormField,其中包含卡号 .

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

Form UI screenshot

这是小部件的代码, DropdownButton

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时都会重建窗口小部件,但是如何将数据保存为尚未存储在任何位置的窗体数据 .

建议请!提前致谢 .

1 回答

  • 1

    使用给定的代码,我能想到的一个错误就是每次创建 TextEditingController .

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

    它应该在 outsidebuild 方法中 . 我们可以在 constructorinitState 中找到它 .

    如果您在 build 之外 _textController ,可以添加更多代码吗?

相关问题