html表单副文本怎么写,11.【文档讲解】表单输入与富文本

3-20【文档讲解】表单输入与富文本

Android、iOS开发者快速上手Flutter-表单输入与富文本

如何获取用户输入?

如何设置输入框的提示文字?

如何显示验证错误信息?

94cbf0485ed0?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image

如何获取用户输入?

我们知道:

在Android中可以通过EditText获取用户输入;

在iOS中可以通过UITextField获取用户输入;

在Flutter中我们可以使用TextField或 TextFormField,然后通过TextEditingController 来获得用户输入。

class _MyFormState extends State {

// 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),

),

);

}

}

如何设置输入框的提示文字?

在Flutter 中,你可以通过向 Text widget 的装饰构造器参数设置一个InputDecoration 来展示“小提示”,或是占位符文字。

body: Center(

child: TextField(

decoration: InputDecoration(hintText: "This is a hint"),

),

)

如何显示验证错误信息?

我们可以TextField的decoration参数为它设置一个InputDecoration,我们借助InputDecoration除了可以添加提示信息外,还可以添加错误信息的提示,具体做法如下:

class _SampleAppPageState extends State {

String _errorText;

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Sample App"),

),

body: Center(

child: TextField(

onSubmitted: (String text) {

setState(() {

if (!isEmail(text)) {

_errorText = 'Error: This is not an email';

} else {

_errorText = null;

}

});

},

decoration: InputDecoration(hintText: "This is a hint", errorText: _getErrorText()),

),

),

);

}

_getErrorText() {

return _errorText;

}

bool isEmail(String emailString) {

String emailRegexp =

r'^((<>()[]\.,;:\s@\"+(.<>()[]\.,;:\s@\"+)*)|(\".+\"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$';

RegExp regExp = RegExp(emailRegexp);

return regExp.hasMatch(emailString);

}

}

然而,我们并不想在一开始就显示错误信息,当用户输入的信息不符合规则时我们就可以借助InputDecoration的 errorText参数来设置错误提示。

通过学习《基于Flutter1.x开发携程网App》获取TextField的更多用法和实战技巧。

94cbf0485ed0?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值