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'), ), ], ); } }