You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用GetX时BottomNavigationBar点击后页面不切换问题

问题解决:底部导航栏点击不切换页面

你的代码核心问题是状态变量定义位置错误:currentIndex和screens被放在了build方法内部。每次调用setState触发组件重构建时,这两个变量都会被重新初始化,currentIndex会被重置为0,导致页面始终停留在第一个标签页。

修正后的代码如下:

class TabScreen extends StatefulWidget {
  const TabScreen({super.key});

  @override
  State<TabScreen> createState() => _TabScreenState();
}

class _TabScreenState extends State<TabScreen> {
  // 将状态变量移到State类的成员区域,避免重构建时被重置
  int currentIndex = 0;
  final List<Widget> screens = [const Text('A'), const Text('B')];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: screens[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

说明

把currentIndex和screens从build方法中移到_TabScreenState类的成员位置后,这些变量会被保留在State实例中,调用setState更新索引时,只会触发build方法重新执行,而变量本身不会被重新初始化,这样就能正确响应底部导航栏的点击,切换对应的页面。

内容的提问来源于stack exchange,提问作者nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:32:39