Search code examples
flutterconditional-statementsflutter-getx

Flutter GetX calling updated variables in Elevated Button onPressed


I'm new to flutter and am trying to wrap my head around the GetX usage. I've watched a few tutorials and have been searching online for a solution. I'm trying to have a button disabled until 2 variables turn true. In my controller I have a method that I can use to check both variables which in turn changes the bool that I use in another file. I cant seem to find the proper place to use the Obx() method inside the elevatedbutton widget.

 class RegistrationController extends GetxController {
      final readTerms = false.obs;
      final readPrivacy = false.obs;
      final enableIntroButton = false.obs;
    
      void isIntroButtonDisabled() {
        if (readTerms.value && readPrivacy.value) {
          enableIntroButton.value = true;
          debugPrint('Button is now enabled');
        }
      }
    }

In my startup screen I have created my instance of my controller at the top of my class to use and in my ElevatedButton widget I figured out how to use Obx on the child: property but that same technique doesnt seem to work in the onPressed part

ElevatedButton(
                  child: Obx(() => regController.enableIntroButton.value
                      ? Text(
                          'Let\'s Get Started',
                          style: TextStyle(fontSize: 20),
                        )
                      : Text('Read Terms & Privacy First')),
                  onPressed: () => regController.enableIntroButton.value
                      ? null
                      : Get.to(() => PhoneRegistrationScreen()),

The rest of the widget is styling so I didnt include it.

Any help would be great. I just finished learning about stateful widgets and using setState lol. So now having discovered GetX I'm trying to relearn the state management.


Solution

  • So after some trial and error and some more online searching I realized that I needed to clarify the regController.value to be equal to false or true rather then just declaring the variable.

    So this was what I had

    onPressed: () => regController.enableIntroButton.value
                          ? null
                          : Get.to(() => PhoneRegistrationScreen()),
    

    and this was what I needed to do...

    onPressed: () => regController.enableIntroButton.value == false
                          ? null
                          : Get.to(() => PhoneRegistrationScreen()),
    

    Although I tried removing the Obx() method right above in the child: property but it didnt seem to work like the onPressed: property so I left it as is.