Flutter GetX 状态变化时触发函数

Mar*_*ert 5 dart flutter flutter-getx

每当我的 GetX 状态发生变化时,如何调用无状态小部件中的特定函数?例如,每当我的底部导航栏的索引发生变化时,如何触发事件?

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

编辑:

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

     void changeIndex(int val) {
          index.value = val;
     }
 }
Run Code Online (Sandbox Code Playgroud)

ert*_*ull 11

获取您的控制器,根据您的要求监听方法的变化。它可能在构造函数、build 方法或按钮的 onPress 方法等中。

BottomNavigationController bnc = Get.find();

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

Run Code Online (Sandbox Code Playgroud)


Lor*_*n.A 6

扩展@ertgrull的答案:

您可以向任何流添加侦听器,但 Getx 还具有用于此类功能的内置工作函数。

onInit通常,当我需要这个时,我会在控制器中添加监听器。

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
    });
  }
}
Run Code Online (Sandbox Code Playgroud)