Flutter GetX trigger function when state changes

Issue

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 consturctor, build method or a button’s onPress method etc.

BottomNavigationController bnc = Get.find();

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

Answered By – ertgrull

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.