dart - Flutter 监听来自其他小部件的 textField 值变化
问题描述
下面是一个使用 textField 和按钮捕获用户输入的对话框。当 textField 为空时,该按钮被禁用,但是当 textField 被填充值时,它继续被禁用。这是因为 _textController.text 状态未更新(在此小部件中再次呈现)。
void _pushAdd() async {
await showDialog(
context: this.context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Add a custom word'),
content: _renderForm(),
actions: <Widget>[
FlatButton(
child: Text('ADD'),
onPressed: (_textController.text.isNotEmpty) ? () => _addNewPair() : null,
),
],
);
},
);
// Changed _pushAdd as async to handle onClose and clear _textController upon exit
_textController.clear();
当前 _textController 在顶部的类中启动(不是 init)。
var _textController = new TextEditingController();
带有 _textController 的 textField 位于此处:
Widget _renderForm() {
return Container(
height: 50.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
autofocus: true,
textCapitalization: TextCapitalization.words,
controller: _textController,
decoration: InputDecoration(
hintText: 'RedPotato',
),
),
]
)
);
}
我最初的计划是使用 onChanged: + 另一种存储文本的状态。但是,我怀疑这样做是否有效。所以我问,实时处理 TextField 值以便其他小部件可以监听更改的标准方法是什么?
解决方案
你只需要听TextEditingController
文本变化。
var _textController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the Widget is disposed
_textController.dispose();
super.dispose();
}
@override
void initState() {
_textController.addListener((){
//here you have the changes of your textfield
print("value: ${_textController.text}");
//use setState to rebuild the widget
setState(() {
});
});
super.initState();
}
For more info check this link : https://flutter.io/docs/cookbook/forms/retrieve-input
推荐阅读
- javascript - 将 DatePicker 中的日期保存在 cookie 中并将日期发送到 Datatable
- html - 阻止直接访问 mp4 视频,同时允许他们使用 web.config 在网站内查看
- sql - SQL 语句中是否加入
- git - 无法访问无法解析主机
- python - 在编写样式器对象时,有没有办法让 add_format 在 xlsxwriter 中工作?
- c# - 我应该如何在视图中检查用户的角色?
- python - 如何在 pandas 的“n”个月分区上滚动数据
- swift - 设置图像以快速切换
- spring-boot - 例外:使用Spring`@DynamicPropertySource`时,只能在容器启动后获取映射端口
- python-3.x - (PySpark) StringIndexer Error: py4j.protocol.Py4JJavaError: An error occurred while calling o46.fit