Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Enable/Disable Button based on TextFormField content

How can I activate/deactivate a button based on the content of a TextFormField?

I want to make sure a user can only press Button X if the TextFormField has 10 entered numbers (if it's a mobile number).

Thanks!

like image 390
DrainBramage Avatar asked Dec 28 '18 20:12

DrainBramage


2 Answers

The state of the widget can be updated in the Form's onChanged callback which is called whenever any of the form fields' value changes. There you can use a form key to validate the form and set a flag to enable/disable the button. This solution allows you to scale to disable buttons in forms with multiple fields. For example,

/// Key used to reference the form.
final _formKey = GlobalKey<FormState>();

...

Form(
  key: _formKey,
  onChanged: () => setState(() => _enableBtn = _formKey.currentState.validate()),
  child: ListView(
    children: <Widget>[
      TextFormField(
        validator: (value) => value.length < 10 ?
          'Number must be at least 10 digits' : // return an error message
          null,
        ...
      ),
    ],
  ),
)

...

FlatButton(
  onPressed: _enableBtn ?
    () => _doSomething() :
    null, // setting onPressed to null disables the button.
  ...
like image 179
Jacob McGowan Avatar answered Sep 19 '22 13:09

Jacob McGowan


A simple way would be to set the autovalidate property of our TextFormField to true. This will automatically detect for changes on our TextFormField widget. We can then try to check if our TextFormField's value has a String length of 10 characters on the validator property . After that we can call setState to enable or disable our button (I use FlatButton in this example).

bool _btnEnabled = false;

...

@override
Widget build(BuildContext context){

  ...

  TextFormField(

    ...
    autovalidate: true,
    validator: (String txt){
      if (txt.length == 10){
        setState((){
          _btnEnabled = true;
        });
      } else {
        setState((){
          _btnEnabled = false;
        });
      }
    }

    ...

  FlatButton(
    onPressed: _btnEnabled == true ? yourCallback : null,
    child: ...
like image 42
Jerome Escalante Avatar answered Sep 18 '22 13:09

Jerome Escalante