Search code examples
flutterdartflutter-getx

Flutter GetX trigger function when state changes


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;
     }
 }

Solution

  • 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
    });