简体   繁体   中英

Custom Validation TextFormField Flutter

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) {},

  ),
)

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

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

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

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.

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.

You shouldn't be using Form widget and TextFormField for displaying error in TextField.

Do validation by controllers instead

For Example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM