import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_loginPageState createState() => _loginPageState();
}
class _loginPageState extends State<MyApp> {
//全局key用来获取form表单
GlobalKey<FormState> loginKey = GlobalKey<FormState>();
//用户名
String userName;
//密码
String password;
void login() {
//获取当前的状态
var loginForm = loginKey.currentState;
//验证form表单
if (loginForm.validate()) {
loginForm.save();
print('username' + userName + 'password' + password);
}
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: '表单组件',
home: Scaffold(
appBar: AppBar(
title: Text('表单组件'),
),
body: Column(
children: <Widget>[
Container(
//添加内边距
padding: const EdgeInsets.all(16.0),
//添加from表单
child: Form(
key: loginKey,
child: Column(
children: <Widget>[
TextFormField(
//装饰器
decoration: InputDecoration(
//提示文本
labelText: '请输入用户名'),
//接收输入值
onSaved: (value) {
userName = value;
},
onFieldSubmitted: (value) {},
),
TextFormField(
decoration: InputDecoration(labelText: '请输入密码'),
onSaved: (val) {
password = val;
},
//是否密文输入
obscureText: true,
//验证表单方法
validator: (val) {
return val.length < 6 ? '密码长度不够6位' : null;
},
)
],
),
),
),
//限定容器大小
SizedBox(
width: 340.0,
height: 42,
//添加登录按钮
child: RaisedButton(
onPressed: login,
child: Text(
'登录',
style: TextStyle(fontSize: 18.0),
),
),
)
],
),
),
);
}
}
网友评论