如何修复Flutter BottomNavigation路由跳转无响应问题?
核心问题
你的代码存在两个关键错误:
- 没有给
NavigationBar设置selectedIndex,点击后导航项没有选中视觉反馈,也无法和当前页面状态绑定 - 没有在
Scaffold的body中根据currentPageIndex切换对应页面,定义的destinations列表完全没用到,末尾的[currentPageIndex]是无效的孤立代码
修复步骤
- 给
NavigationBar添加selectedIndex: currentPageIndex,绑定当前选中索引 - 修改
body部分,用destinations[currentPageIndex]渲染当前页面(如果需要保留ResponsiveScreen,就把页面放在它内部) - 删除代码末尾无效的
[currentPageIndex]
修正后的关键代码片段
class _LevelSelectionScreenState extends State<LevelSelectionScreen> { int currentPageIndex = 0; final destinations = [ const MainMenuScreen(), const AvailabilityScreen(), const SettingsScreen(), ]; @override Widget build(BuildContext context) { final playerProgress = context.watch<PlayerProgress>(); return Scaffold( extendBody: true, bottomNavigationBar: Container( child: NavigationBar( // 新增:绑定选中索引,实现导航项选中视觉反馈 selectedIndex: currentPageIndex, onDestinationSelected: (int index) { setState(() { currentPageIndex = index; }); }, destinations: const <Widget>[ NavigationDestination( selectedIcon: Icon(Icons.home), icon: Icon(Icons.home_outlined), label: 'Home', ), NavigationDestination( selectedIcon: Icon(Icons.book), icon: Icon(Icons.book_outlined), label: 'Learn', ), NavigationDestination( selectedIcon: Icon(Icons.person), icon: Icon(Icons.person_outlined), label: 'Profile', ), ], ), ), // 修改:根据当前索引切换展示对应页面 body: ResponsiveScreen( // 把当前选中的页面作为ResponsiveScreen的子组件 child: destinations[currentPageIndex], // 保留你原来ResponsiveScreen的其他参数 // ... ), ); } }
额外说明
如果你的ResponsiveScreen是固定布局框架,只需要将内部的页面部分替换为destinations[currentPageIndex]即可,确保页面切换逻辑和导航选中状态同步。
内容的提问来源于stack exchange,提问作者Elena Epshtein
相关产品推荐
相关产品推荐

