表单是一个包含表单元素的区域。表单元素允许用户输入内容,比如文本域,下拉列表,单选框,复选框等。常见应用场景有:登录、注册、输入信息等。表单里有两个重要的组件,一个是Form组件,用来左整个表单提交使用的;另一个是TextFormField组件,用来做用户输入的。
Form组件常用属性
属性名 | 类型 | 说明 |
---|---|---|
key | Key | 组件在整个Widget树中的key值 |
autovalidate | bool | 是否自动提交表单 |
child | Widget | 组件child只能有一个子组件 |
onChanged | VoidCallback | 当FormField值改变时的回调函数 |
TextFormField组件常用属性
属性名 | 类型 | 说明 |
---|---|---|
autovalidate | bool | 自动验证值 |
initialValue | T | 表单字段初始值 |
onSaved | FormFieldSetter<T> | 当Form表单调用保存方法Save时,回调的函数 |
validator | FormFieldValidate<T> | Form表单验证器 |
示例
import 'package:flutter/material.dart';
void main() => runApp(LoginPage());
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
GlobalKey<FormState> _loginKey = GlobalKey<FormState>();
String _userName;
String _password;
void _login() {
var _loginForm = _loginKey.currentState;
if (_loginForm.validate()) {
_loginForm.save();
print('name: $_userName, password: $_password');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: const EdgeInsets.all(10.0),
child: Form(
key: _loginKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: '请输入用户名',
),
onSaved: (value) {
print('onSaved :$value');
_userName = value;
},
onFieldSubmitted: (value) {
print('onFieldSubmitted : $value');
},
),
TextFormField(
decoration: InputDecoration(
labelText: '请输入密码',
),
obscureText: true,
onSaved: (value) {
_password = value;
},
validator: (value) {
return value.length < 6 ? '密码长度不够6位' : null;
},
),
Container(
margin: const EdgeInsets.only(top: 20.0),
width: 400.0,
height: 40.0,
child: RaisedButton(
onPressed: () {
_login();
},
child: Text('登录'),
),
),
],
)),
)
],
),
),
),
);
}
}
效果显示: