用于搜集不一样类型的用户输入,用户填好数据,点击按钮submit,软件须要对数据进行验证,验证有误须要提示用户html
Flutter提供很是直观的操做方式,以下图app
Form & FormField Widgetide
最简单的验证是一个Form内包含多个TextFormFieldui
//初始化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两个属性this
在例子里能够直接使用控件3d
final form = _formKey.currentState;
实现代码code
/// 编辑框 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,) ], )), ), ); } }