Form表單
用於搜集不同類型的用戶輸入,用戶填好數據,點擊按鈕submit,軟件需要對數據進行驗證,驗證有誤需要提示用戶
Flutter提供非常直觀的操作方式,如下圖

Form & FormField Widget
最簡單的驗證是一個Form內包含多個TextFormField
//初始化FormState
final _formKey = new GlobalKey<FormState>();
String username;
...
new Form(
key: formKey,
child: new TextFormField(
onFieldSubmitted:(v)=>print("submit"),
onSaved: (val)=> this._name = val,
validator: (val)=> (val == null || val.isEmpty) ? "請輸入商品名稱": null,
decoration: new InputDecoration(
labelText: '商品名稱',
),
),
);
這里需要注意 TextFormField的onSaved, validator兩個屬性
- 當調用FormFieldState#validate如果字段設置了validator事件,那么
validator會接收到當前字段的值,如果無錯誤返回null值,否則返回錯誤提示信息, - validator通過后調用FormFieldState#save 觸發onSaved事件,保存提交的內容
- key是每個flutter Widget的身份標識, 可以直接引用到控件
在例子里可以直接使用控件
final form = _formKey.currentState;
實現代碼
/// 編輯框
class _ProductEditorState extends State<ProductEditor> {
GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
String _name;
String _color;
String _config;
void _onSubmit() {
final form = _formKey.currentState;
if(form.validate()) {
form.save();
showDialog(context: context, builder: (ctx)=> new AlertDialog(
content: new Text('$_name $_color $_config'),
));
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('新增商品'),),
body: new Padding(
padding: const EdgeInsets.all(8.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new TextFormField(
onSaved: (val)=> this._name = val,
validator: (val)=> (val == null || val.isEmpty) ? "請輸入商品名稱": null,
decoration: new InputDecoration(
labelText: '商品名稱',
),
),
new TextFormField(
maxLength: 32, //文本長度
onSaved: (val)=> this._color = val,
validator: (v)=>(v == null || v.isEmpty)?"請選擇顏色": null,
decoration: new InputDecoration(
labelText: '顏色',
),
),
new TextFormField(
maxLength: 32,
onSaved: (val)=> this._config = val,
validator: (v)=>(v == null || v.isEmpty)?"請選擇配置": null,
decoration: new InputDecoration(
labelText: '配置',
),
),
new MaterialButton(child: new Text('Submit', style: const TextStyle(color: Colors.white),),onPressed: _onSubmit, color: Theme.of(context).primaryColor,)
],
)),
),
);
}
}
