本頁面介紹如何在Flutter應(yīng)用程序中輸入文本
TextField 是最常用的文本輸入widget.
默認(rèn)情況下,TextField有一個(gè)下劃線裝飾(decoration)。您可以通過提供給decoration屬性設(shè)置一個(gè)InputDecoration來添加一個(gè)標(biāo)簽、一個(gè)圖標(biāo)、提示文字和錯(cuò)誤文本。 要完全刪除裝飾(包括下劃線和為標(biāo)簽保留的空間),將decoration明確設(shè)置為空即可。
TextFormField包裹一個(gè)TextField 并將其集成在Form中。你要提供一個(gè)驗(yàn)證函數(shù)來檢查用戶的輸入是否滿足一定的約束(例如,一個(gè)電話號碼)或當(dāng)你想將TextField與其他FormField集成時(shí),使用TextFormField。
有兩種獲取用戶輸入的主要方法:
每當(dāng)用戶輸入時(shí),TextField會調(diào)用它的onChanged回調(diào)。 您可以處理此回調(diào)以查看用戶輸入的內(nèi)容。例如,如果您正在輸入搜索字段,則可能需要在用戶輸入時(shí)更新搜索結(jié)果。
一個(gè)更強(qiáng)大(但更精細(xì))的方法是提供一個(gè)TextEditingController作為TextField的controller屬性。 在用戶輸入時(shí),controller的text和selection屬性不斷的更新。要在這些屬性更改時(shí)得到通知,請使用controller的addListener方法監(jiān)聽控制器 。 (如果你添加了一個(gè)監(jiān)聽器,記得在你的State對象的dispose方法中刪除監(jiān)聽器 )。
該TextEditingController還可以讓您控制TextField的內(nèi)容。如果修改controller的text或selection的屬性,TextField將更新,以顯示修改后的文本或選中區(qū)間。 例如,您可以使用此功能來實(shí)現(xiàn)推薦內(nèi)容的自動補(bǔ)全。
以下是使用一個(gè)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'),
),
],
);
}
}
更多建議: