Search code examples
buttonkeyboardfluttertextfieldflutter-layout

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!


Solution

  • 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: ...