如何使用GetX Flutter更改小部件的状态

ssm49v7z  于 2023-04-22  发布在  Flutter
关注(0)|答案(1)|浏览(189)

我想这个小部件(TabButton)改变其状态,并运行isSelected func ever currentPageIndex值在控制器中的变化。
我的小部件:

Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Obx(
            () => TabButton(
              title: 'AGORA',
              onPress: () => widget.pageController.jumpToPage(0),
              isSelected: _controller.isSelected(0),
            ),
          ),
          Obx(
            () => TabButton(
              title: 'AGENDA',
              onPress: () => widget.pageController.jumpToPage(1),
              isSelected: _controller.isSelected(1),
            ),
          ),
          Obx(
            () => TabButton(
              title: 'FAVORITOS',
              onPress: () => widget.pageController.jumpToPage(2),
              isSelected: _controller.isSelected(2),
            ),
          ),
        ],
      ),

我的控制器:

class RootScreenController extends GetxController {
  Rx<int> currentPageIndex = 1.obs;

  // It's called in PageView
  void pageChangged(int index) {
    currentPageIndex.value = index;
  }

  bool isSelected(int buttonIndex){
    return currentPageIndex.value == buttonIndex;
  }
}

我不知道我做错了什么,但按钮的状态没有改变。

j5fpnvbx

j5fpnvbx1#

您需要确保Obx小部件正确侦听Rx currentPageIndex中的更改。

Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Obx(
        () => TabButton(
          title: 'AGORA',
          onPress: () => widget.pageController.jumpToPage(0),
          isSelected: _controller.currentPageIndex.value == 0,
        ),
      ),
      Obx(
        () => TabButton(
          title: 'AGENDA',
          onPress: () => widget.pageController.jumpToPage(1),
          isSelected: _controller.currentPageIndex.value == 1,
        ),
      ),
      Obx(
        () => TabButton(
          title: 'FAVORITOS',
          onPress: () => widget.pageController.jumpToPage(2),
          isSelected: _controller.currentPageIndex.value == 2,
        ),
      ),
    ],
  )

这一修改将确保Obx小部件直接观察currentPageIndex.value,这将在currentPageIndex值更改时产生正确的行为。

相关问题