我是 Flutter 的新手,正在尝试使用 Sateful 小部件。事情是这样的,在我的 UI 屏幕布局中,我有两个不同的小部件
- DropdownButton 小部件
- 保存卡号的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
方法的外部。我们可以在 constructor
或 initState
中使用它。
如果您在 build 之外有 _textController
,您可以添加更多代码吗?
关于user-interface - setState() 清除表单元素数据flutter中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125575/