自定义验证TextFormField Flutter [英] Custom Validation TextFormField Flutter

查看:473
本文介绍了自定义验证TextFormField Flutter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我里面有Form和TextFormField:

I have Form and TextFormField inside it :

 new Expanded(
  child: TextFormField(
    style: new TextStyle(color: Colors.white),
    keyboardType: TextInputType.text,
    validator: (String value) {
      if (value.length <= 5) {
       //Show error as a Snackbar
      }
    },
    onSaved: (String value) {},

  ),
)

在Buttom印刷机上,我正在检查所有字段是否都有效:

On a Buttom press I am checking if all the fields are validate :

 if (_formKey.currentState.validate()) {
      _submit();
 }

现在的问题是,当您调用validate()并且不返回validate()方法中的任何文本时,它将认为它返回true.

Now the issue is when you call validate() and don't return any text in validate() method then it will consider it return true.

我不想在textField下显示错误,而是要显示为Snackbar.

I don't want to show error below the textField but as a Snackbar.

此外,我尝试在每个验证器方法中设置一个额外的标志并进行设置,但是如果表单中有多个字段,它会变得很复杂.

Also, I tried setting an extra flag and setting in each validator Method but it gets complex if there are multiple fields in the form.

谁能告诉我如何处理_formKey.currentState.validate()应该返回false和validator方法的情况? TextFormField内部不需要返回错误文本.

Can anyone tell me how can I handle this situation where _formKey.currentState.validate() should return false and validator method inside TextFormField need not to return error text.

推荐答案

如果您不想在TextField中显示错误,则不应使用 Form 小部件和 TextFormField .

You should be not user Form widget and TextFormField if you want to not display error in TextField.

您应该由控制器进行验证

You should be do validation by controllers

例如

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  final _text = TextEditingController();
  bool _validate = false;

  @override
  void dispose() {
    _text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Error Showed if Field is Empty on Submit button Pressed'),
            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'Enter the Value',
              ),
            ),
            RaisedButton(
              onPressed: () {
                        if(_text.text.length<=5){
                    // open dialog
                  }
              },
              child: Text('Submit'),
              textColor: Colors.white,
              color: Colors.blueAccent,
            )
          ],
        ),
      ),
    );
  }
}

这篇关于自定义验证TextFormField Flutter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆