import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '登录表单验证 Form',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: MyHomePage(title: '登录表单验证 Form'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _unameController = new TextEditingController();
TextEditingController _pwdController = new TextEditingController();
GlobalKey _formKey = new GlobalKey<FormState>(); // 为了通过 Globalkey找到该state
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0,horizontal: 24.0),
child: Form(
key: _formKey,
autovalidate: true, // 开启自动校验
child: Column(
children: <Widget>[
TextFormField(
autofocus: true,
controller: _unameController,
decoration: InputDecoration(
labelText: '用户名',
hintText:'用户名或邮箱',
icon: Icon(Icons.perm_contact_calendar),
),
// 校验
validator: (v){
return v
.trim()
.length > 0 ? null: '用户名不能为空';
},
),
TextFormField(
controller: _pwdController,
decoration: InputDecoration(
labelText: '密码',
hintText: '输入密码',
icon: Icon(Icons.lock),
),
obscureText: true,
validator: (v){
return v
.trim()
.length > 5 ? null : '密码不能少于6位';
},
),
// 登录按钮
Padding(
padding: const EdgeInsets.only(top: 28.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
padding: EdgeInsets.all(15.0),
child: Text('登录'),
color: Theme.of(context).primaryColor,
textColor: Colors.white,
onPressed: (){
if ((_formKey.currentState as FormState).validate()){
debugPrint('验证通过提交');
}
},
),
)
],
),
)
],
)
),
),
);
}
}
代码显示效果
网友评论