11.表单输入与富文本
声明:Flutter专栏文档均来自慕课网 https://coding.imooc.com/class/321.html
Android、iOS开发者快速上手Flutter-表单输入与富文本
如何获取用户输入?
如何设置输入框的提示文字?
如何显示验证错误信息?
image
如何获取用户输入?
我们知道:
在Android中可以通过
EditText获取用户输入;在iOS中可以通过
UITextField获取用户输入;
在Flutter中我们可以使用TextField或 TextFormField,然后通过TextEditingController 来获得用户输入。
class _MyFormState extends State<MyForm> {
// Create a text controller and use it to retrieve the current value.
// of the TextField!
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when disposing of the Widget.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
// When the user presses the button, show an alert dialog with the
// text the user has typed into our text field.
onPressed: () {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
// 通过TextEditingController获取用户输入
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: Icon(Icons.text_fields),
),
);
}
}大家可以通过《基于TextField实现顶部SearchBar》案例来学习输入框的更多用法和实战技巧,可以通过Flutter Cookbook中的Retrieve the value of a text field获得更多信息。
如何设置输入框的提示文字?
在Flutter 中,你可以通过向 Text widget 的装饰构造器参数设置一个InputDecoration 来展示“小提示”,或是占位符文字。
如何显示验证错误信息?
我们可以TextField的decoration参数为它设置一个InputDecoration,我们借助InputDecoration除了可以添加提示信息外,还可以添加错误信息的提示,具体做法如下:
然而,我们并不想在一开始就显示错误信息,当用户输入的信息不符合规则时我们就可以借助InputDecoration的 errorText参数来设置错误提示。
通过学习《基于Flutter1.x开发携程网App》获取TextField的更多用法和实战技巧。
image
Last updated
Was this helpful?