flutterandroid-studiodartflutter-layoutdart-ui

How to disable a button in flutter untill all Text feilds are filled


I have a registration form with multiple text feilds and a Radio button and a birthdate picker. I want to disable the submit button untill the user key in all the required feilds. I managed to do something but it only validates one text feild.


 bool activateTheButton =false;

@override
 initState(){
   super.initState();
    nameController = TextEditingController();

    nameController.addListener(() {
      final activateTheButton = nameController.text.isNotEmpty;
      setState(() => this.activateTheButton = activateTheButton);

   ......................
ElevatedButton( onPressed: activateTheButton
             ? (){

         }: null,

 }

How can I make it so that all the textfeilds along with the radio button and date of birth must have data first then activate button?

your help is highly appreciated.


Solution

  • Have a variable that enables/disables the button:

    bool _disabled = true;
    

    Use IgnorePointer and Opacity for the button:

    IgnorePointer(
      ignoring: _disabled;
      child: Opacity(
        opacity: _disabled ? 0.5 : 1.0,
        child: YourButton(...),
      )
    )
    

    You are going to have controllers for each TextFields;

    TextEditingController _controllerOne;
    TextEditingController _controllerTwo;
    

    Use the TextField's onChanged: (value) {} to call a method that handles the _disabled variable:

    TextField(
      controller: _controllerOne,
      onChanged: (text) {
        _setDisabled();
      },
    ),
    
    _setDisabled() {
       if (_controllerOne.text != "" && _controllerTwo.text != "") {
          setState(() {_disabled = false;});
       } else {
          setState(() {_disabled = true;});
       }
    }