TextField是最常用的文本输入widget。
默认情况下,TextField有一个下划线装饰(decoration)。你可以通过提供给decoration属性设置一个InputDecoration来添加一个标签、一个图标、提示文字和错误文本。要完全删除装饰(包括下划线和为标签保留的空间),将decoration明确设置为空即可。
TextFormField包裹一个TextField并将其集成在Form中。你要提供一个验证函数来检查用户的输入是否满足一定的约束(例如,一个电话号码)或当你想将TextField与其他FormField集成时,使用TextFormField.
获取用户输入
有两种获取用户输入的主要方法:
1.处理onChanged回调
2.提供一个TextEditingController。
onChanged
当用户输入时,TextField会调用它的onChanged回调。你可以处理此回调以查看用户输入的内容。例如,你在输入搜索字段,则可能需要在用户输入时更新搜索结果。
TextEditingController
一个更强大(但更精细)的方法是提供一个TextEditingController作为TextField的controller属性。在用户输入时,controller的text和selection属性不断的更新。要在这些属性更改时得到通知,可以使用controller的addListener方法监听控制器,(如果你添加了一个监听器,记得在你的State对象的dispose方法中删除监听器)。
该TextEditingController还可以让你控制TextField的内容。如果修改controller的text或selection的属性,TextField将更新,以显示修改后的文本或选中区间,例如,你可以使用此功能实现推荐内容的自动补全。
例子
以下是使用一个TextEditingController
读取TextField中用户输入的值的示例:
/// Opens an [AlertDialog] showing what the user typed. class ExampleWidget extends StatefulWidget { ExampleWidget({Key key}) : super(key: key); @override _ExampleWidgetState createState() => new _ExampleWidgetState(); } /// State for [ExampleWidget] widgets. class _ExampleWidgetState extends State<ExampleWidget> { final TextEditingController _controller = new TextEditingController(); @override Widget build(BuildContext context) { return new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new TextField( controller: _controller, decoration: new InputDecoration( hintText: 'Type something', ), ), new RaisedButton( onPressed: () { showDialog( context: context, child: new AlertDialog( title: new Text('What you typed'), content: new Text(_controller.text), ), ); }, child: new Text('DONE'), ), ], ); } }