如何使用颤振 GetX 将'selectedIndex'的值从一个飞镖文件更改为另一个飞镖文件?



我在一个dart文件中有我的自定义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:包装项目小部件

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.

有人能给我一些代码和解释的解决方案吗?此外,我将如何设置一个特定的屏幕作为初始屏幕

用此代码替换点击

onTap: () {
selectedIndex.value = 1; // page index you want to view
},

然后删除bnbItems窗口小部件上的Obx(()=>

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

然后在主体的小部件上使用Obx(()=>包装

body: Obx(() => screen[selectedIndex.value]),

为什么在GetX结构中使用setState?

尝试onTap()的此代码

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

以在CCD_ 13中设置该屏幕的初始屏幕使用索引no而不是0。

最新更新