如何使用flutter GetX将'selectedIndex'的值从一个dart文件更改到另一个dart文件?

cu6pst1q  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(149)

我在一个dart文件中有我的***custom***Bottom Navigation Bar,即bottomnavbar.dart。我在home.dart文件中有多个screens(或页面)的列表。我正在使用.obs variable来存储我选择的索引值。
home.dart文件中代码:

var selectedIndex = 0.obs;
final screen = [
  const Page1(),
  const Page2(),
  const Page3(),
  const Page4(),
  const Page5(),
];
...
body: screen[selectedIndex.value],
...

即使我改变了变量值(如0.obs1.obs),页面也不会改变,为什么?
接下来,在我的bottomnavbar.dart文件中,我提取并为我的nav bar 'items'创建了一个小部件。我尝试用Obx Package 项目小部件:

Widget bnbItems(String image, int index, double height) {
return Obx(
  () => InkWell(
    splashColor: Theme.of(context).brightness == Brightness.dark
        ? Colors.white.withOpacity(0.5)
        : Colors.pink.withOpacity(0.5),
    enableFeedback: true,
    onTap: () => setState(() {
      selectedIndex.value = index;
      _controller.animateTo(index / 4);
      // print(selectedIndex);
    }),
    child: Container(
      alignment: Alignment.center,
      width: 50,
      height: 50,
      child: Padding(
        padding: const EdgeInsets.only(top: 5.0),
        child: Image.asset(
          image,
          height: height,
        ),
      ),
    ),
  ),
);}

而我得到这个错误:

[Get] the improper use of a GetX has been detected. 
      You should only use GetX or Obx for the specific widget that will be updated.
      If you are seeing this error, you probably did not insert any observable variables into GetX/Obx 
      or insert them outside the scope that GetX considers suitable for an update 
      (example: GetX => HeavyWidget => variableObservable).
      If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX.
有人能给予我一些代码和解释的解决方案吗?还有我如何能够将一个特定的屏幕设置为初始屏幕?
ngynwnxp

ngynwnxp1#

为什么要在GetX结构中使用setState?
请为onTap()尝试以下代码

onTap: () {
  selectedIndex.value = index;
  _controller.animateTo(index / 4);
  // print(selectedIndex);
},

为了设置初始屏幕,使用var selectedIndex = 0.obs;中屏幕索引号而不是0。

相关问题