Flutter(二)Form Validating(表单验证)

Form表单

用于搜集不同类型的用户输入,用户填好数据,点击按钮submit,软件需要对数据进行验证,验证有误需要提示用户

Flutter提供非常直观的操作方式,如下图

image

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,)
            ],
        )),
      ),
    );
  }

}
posted @ 2018-04-25 16:50  TryHard  阅读(11463)  评论(0编辑  收藏  举报