Search code examples
flutterflutter-getx

Using getx obx and GetX state management inside getx dialog flutter


I am using Get dialog in my app and I want to use GetX state management inside my dialog widget for example I have checkbox inside my dialog and I want to update it's state with GetX however when I use the GetX<AppController>() inside my get dialog I ran into following error

You should only use GetX or Obx for the specific widget that will be updated. If you are seeing this error, you probably did not insert any observable variables into GetX/Obx or insert them outside the scope that GetX considers suitable for an update (example: GetX => HeavyWidget => variableObservable). If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. Here is the sample code:

Get.dialog(
      Dialog(
        child: Flexible(
            child: GetX<AppController>(
              init: appController,
              builder: (val){
                return CheckboxListTile(
                  title: Text("Power off computer"),
                  contentPadding: EdgeInsets.zero,
                  value: appController.powerOffRaspberry,
                  onChanged: (newValue) {
                    appController.powerOffRaspberry = !appController.powerOffRaspberry;
                  },
                  controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
                );
              },
            )
        ),
      ),

    )

Solution

  • Make appController.powerOffRaspberry observable:

    final powerOffRaspberry = false.obs; 
    

    Update CheckboxListTile as:

    CheckboxListTile(
                  title: Text("Power off computer"),
                  contentPadding: EdgeInsets.zero,
                  value: appController.powerOffRaspberry.value,
                  onChanged: (newValue) {
                    appController.powerOffRaspberry.value = !appController.powerOffRaspberry.value;
                  },
                  controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
                )