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

Flutter底部导航栏无法切换页面问题求助

解决Flutter底部导航栏无法切换页面的问题

你的代码核心问题是**_selectedIndex变量定义在build方法内部**。每次调用setState()时,build方法会重新执行,此时_selectedIndex = 0会被再次触发,导致选中索引被强制重置为0,页面始终停留在首页。

修改方案

需要把状态变量、页面列表以及点击回调移到State类的成员位置,而非build方法内部,这样它们的状态才能在组件生命周期内被正确保存。

修改后的完整代码

class TabNav extends StatefulWidget {
  const TabNav({Key? key}) : super(key: key);

  @override
  State<TabNav> createState() => _TabNavState();
}

class _TabNavState extends State<TabNav> {
  // 移到State类作为成员变量,持久保存选中状态
  int _selectedIndex = 0;

  // 页面列表移到外部,避免每次build重复创建
  final List<Widget> _pages = const <Widget>[
    HomeTab(),
    RoomsTab(),
    SearchTab(),
    MapsTab(),
    ProfileTab()
  ];

  // 点击回调移到外部,提升性能
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _selectedIndex,
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.transparent,
        onTap: _onItemTapped,
        type: BottomNavigationBarType.shifting,
        iconSize: 30,
        unselectedItemColor: Colors.black,
        selectedIconTheme: const IconThemeData(color: Colors.black, size: 30),
        selectedItemColor: Colors.black,
        selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold),
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.door_back_door),
            label: 'Rooms',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Search',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.map),
            label: 'Maps',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
      ),
    );
  }
}

关键说明

  • 状态变量放在State类中,能确保setState()更新后的值被保留,不会在build时被重置。
  • 将页面列表和回调函数移到build外,可避免每次组件重建时重复创建这些对象,提升整体性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:50:25