使用了Form、TextFormField
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
String _name;
String _password;
// 提交
void _onSubmit() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
_showMessage('用户名是:$_name,密码是:$_password');
}
}
// 展示提示框
void _showMessage(String val) {
showDialog<Null>(
context: context,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('提示'),
content: Text('$val'),
actions: <Widget>[
FlatButton(
onPressed: () {
_formKey.currentState.reset();
Navigator.pop(context);
},
child: Text('确定'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('我是title'),
),
body: ListView(
children: <Widget>[
Form(
key: _formKey,
onChanged: () {
print('onChanged');
},
child: new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(
labelText: '用户名',
),
onSaved: (val) => this._name = val,
validator: (val) {
if (val == null || val.isEmpty) {
return '请输入用户名';
}
if (val.length > 18 || val.length < 6) {
return '用户名长度在6-18字符之间';
}
return null;
}
),
new TextFormField(
decoration: new InputDecoration(
labelText: '密码',
),
onSaved: (val) => this._password = val,
validator: (val) {
if (val == null || val.isEmpty) {
return '请输入密码';
}
if (val.length != 6) {
return '密码应为6位字符';
}
return null;
}
),
new Row(
children: <Widget>[
MaterialButton(
onPressed: () {
_formKey.currentState.reset();
_showMessage('用户名密码已经重置');
},
child: Text('重置'),
),
MaterialButton(
onPressed: _onSubmit,
child: Text('提交'),
),
],
),
],
),
)
],
),
);
}
}
结果:


网友评论