Flutter GetX trigger function when state changes

Viewed 9045

How can I call a specific function in my stateless widget, whenever my GetX state changes? E.g. whenever the index of my bottomnavigationbar changes, how can I trigger an event?

    Obx(
        () =>
           BottomNavigationBar(
               items: const <BottomNavigationBarItem>[
                  BottomNavigationBarItem(
                   icon: Icon(Icons.explore),
                   label: 'Erkunden',
                  ),           
               ],
               currentIndex: bottomNavigationController.index.value,
               onTap: (index) {
                     bottomNavigationController.changeIndex(index);
               },
            )
     ),

EDIT:

 class BottomNavigationController extends GetxController {
     RxInt index = 0.obs;

     void changeIndex(int val) {
          index.value = val;
     }
 }
4 Answers

Get your controller, listen changes in a method according to your requirements. It may be in constructor, build method, or a button's onPress method etc.

BottomNavigationController bnc = Get.find();

bnc.index.listen((val) {
  // Call a function according to value
});

To expand on @ertgrull's answer:

You can add a listener to any stream, but Getx also has built in worker functions for this type of functionality.

Usually when I need this I add the listener in the onInit of the controller.

class BottomNavigationController extends GetxController {
  RxInt index = 0.obs;

  void changeIndex(int val) {
    index.value = val;
  }

  @override
  void onInit() {
    super.onInit();

    ever(index, (value) {
  // call your function here
  // any code in here will be called any time index changes
    });
  }
}

if you want to use Obx you have to use Streams first create a Controller

in this example i want to just listen to changes of a number

class AutoLoginCheck extends GetxController {
   var num= "0".obs;

void checkNum() {
    if (num.value == "1") {
      num.value = "0";
    } else {
      num.value = "1";
    }
  }

we can use this function to call that number changing

onTap: () {
   num.checkLoginVal();
                            },

If you are using a GetxController, you can listen to the value in the controller anywhere by adding .obs to the value you would like to listen to.

After adding .obs in the controller the method to listen is the same as the accepted answer.

Related