main.dart
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
title: 'simple login',
home: AppPage(),
)
);
}
class AppPage extends StatelessWidget {
//全局key
GlobalKey<FormState> _globalKey = GlobalKey();
String _username;
String _password;
//登录函数处理
void _login() {
var loginForm = _globalKey.currentState;
if (loginForm.validate()) {
loginForm.save();
print('user name = $_username --- password = $_password');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('simple login'),
),
body: Container(
margin: EdgeInsets.all(16.0),
child: Center(
child: Form(
key: _globalKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: '请输入用户名',
hintText: '请输入用户名',
border: OutlineInputBorder()
),
onSaved: (val){ //数据
_username = val;
},
onFieldSubmitted: (val){
},
validator: (val){ //校验
if(val.length == 0) return '用户名不为空';
},
),
SizedBox(height: 30.0,),
TextFormField(
decoration: InputDecoration(
labelText: '请输入密码',
hintText: '请输入密码',
border: OutlineInputBorder()
),
onSaved: (val){
_password = val;
},
onFieldSubmitted: (val){
},
validator: (val){
if(val.length < 3) return '密码不能小于3个字符';
if(val.length > 6) return '密码不能大于6个字符';
else return null;
},
),
Container(
margin: EdgeInsets.only(top: 30.0),
child: SizedBox(
width: 400.0,
height: 45.0,
child: RaisedButton(
onPressed: _login, //点击事件处理
child: Text('登录',
style: TextStyle(color: Colors.blue, fontSize: 20.0,
),
),
),
),
)
],
),
),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
效果: