Flutter(二)Form Validating(表單驗證)

Form表單

用於蒐集不一樣類型的用戶輸入,用戶填好數據,點擊按鈕submit,軟件須要對數據進行驗證,驗證有誤須要提示用戶html

Flutter提供很是直觀的操做方式,以下圖app

image

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

  • 當調用FormFieldState#validate若是字段設置了validator事件,那麼
    validator會接收到當前字段的值,若是無錯誤返回null值,不然返回錯誤提示信息,
  • validator經過後調用FormFieldState#save 觸發onSaved事件,保存提交的內容
  • key是每一個flutter Widget的身份標識, 能夠直接引用到控件

在例子裏能夠直接使用控件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,)
            ],
        )),
      ),
    );
  }

}
相關文章
相關標籤/搜索