表單是一個包含表單元素的區域。表單元素允許用戶輸入內容,比如:文本域、下拉列表、單選框、複選框等。常見的應用場景有:登錄、註冊、輸入信息等。表單裏有連個重要的組件,一個是Form組件,用來做整個表單提交使用;另一個是TextFormField組件,用來做用戶輸入的。
Form組件屬性:
屬性名 |
類型 |
說明 |
key |
Key |
組件在整個Widget樹中的key值 |
autovalidate |
bool |
是否自動提交表單 |
child |
Widget |
組件child只能有一個子組件 |
onChanged |
VoidCallback |
當FormFiled值改變時的回調函數。 |
TextFormField組件屬性:
屬性名 |
類型 |
說明 |
autovalidate |
bool |
自動驗證值 |
initialValue |
T |
表單字段初始值,比如:輸入收貨地址時,默認回填本的地址信息。 |
onSaved |
FormFieldSetter<T> |
當Form表單調用保存方法Save時回調的函數。 |
validator |
FormFieldValidator<T> |
Form表單驗證器 |
對於輸入框我們最關心的事輸入內容是否合法,比如郵箱地址時否正確,電話號碼是否是數字,等等。等用戶輸入完成後,需要知道輸入框輸入的內容。
爲了獲取表單的實例,我們需要設置一個全局類型的key,通過這個key的屬性,來獲取表單對象。需要使用GlobalKey來獲取,代碼如下所示:
GlobalKey<FormState> loginKey = new GlobalKey<FormState>();
完整代碼:
import 'package:flutter/material.dart';
void main() => runApp(new HomePage());
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
String _name;
String _password;
void _forSubmitted() {
var _form = _formKey.currentState;
if (_form.validate()) {
_form.save();
print(_name);
print(_password);
}
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new MaterialApp(
title: 'Flutter data',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Flutter Form'),
),
floatingActionButton: new FloatingActionButton(
onPressed: _forSubmitted,
child: new Text('提交'),
),
body: new Container(
padding: const EdgeInsets.all(16.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(
labelText: 'Your Name',
),
onSaved: (val) {
_name = val;
},
),
new TextFormField(
decoration: new InputDecoration(
labelText: 'Password',
),
obscureText: true,
validator: (val) {
return val.length < 4 ? "密碼長度錯誤" : null;
},
onSaved: (val) {
_password = val;
},
),
],
),
),
),
),
);
}
}