每当我的 GetX 状态发生变化时,如何调用无状态小部件中的特定函数? 例如。每当底部导航栏的索引发生变化时,如何触发事件?
Obx(
() =>
BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.explore),
label: 'Erkunden',
),
],
currentIndex: bottomNavigationController.index.value,
onTap: (index) {
bottomNavigationController.changeIndex(index);
},
)
),
编辑:
class BottomNavigationController extends GetxController {
RxInt index = 0.obs;
void changeIndex(int val) {
index.value = val;
}
}
答案 0 :(得分:1)
获取您的控制器,根据您的要求监听方法中的更改。它可能在constructor、build 方法或按钮的onPress 方法等中。
BottomNavigationController bnc = Get.find();
bnc.index.listen((val) {
//call a function according to value
});
答案 1 :(得分:1)
扩展@ertgrull 的回答:
您可以向任何流添加侦听器,但 Getx 还为此类功能内置了 worker functions。
通常当我需要这个时,我会在控制器的 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
});
}
}
答案 2 :(得分:0)
如果你想使用 Obx 你必须使用 Streams 首先创建一个控制器
在这个例子中,我只想听一个数字的变化
class AutoLoginCheck extends GetxController {
var num= "0".obs;
void checkNum() {
if (num.value == "1") {
num.value = "0";
} else {
num.value = "1";
}
}
我们可以使用这个函数来改变那个号码
onTap: () {
num.checkLoginVal();
},
答案 3 :(得分:0)
如果您使用的是 GetxController,您可以通过将 .obs
添加到您想要监听的值中来监听控制器中任何位置的值。
在控制器中添加 .obs 后,监听方法与接受的答案相同。