Flutter中为salomon_bottom_bar添加页面路由的方法求助
解决salomon_bottom_bar实现页面路由的问题
你可以通过维护选中状态+页面容器组件来实现路由切换,这个包本身只负责底部导航的UI,路由逻辑需要结合Flutter的状态管理和页面组件自行实现,以下是完整实现方案:
1. 基础准备:管理选中索引状态
用StatefulWidget维护当前选中的导航项索引,同时定义对应每个导航项的页面列表:
class MyBottomNavPage extends StatefulWidget { const MyBottomNavPage({super.key}); @override State<MyBottomNavPage> createState() => _MyBottomNavPageState(); } class _MyBottomNavPageState extends State<MyBottomNavPage> { // 当前选中的导航索引 int _currentIndex = 0; // 导航项对应的页面集合 final List<Widget> _pages = const [ HomePage(), LikesPage(), ProfilePage(), ];
2. 配置底部导航的点击回调
在SalomonBottomBar的onTap参数中,更新选中索引并触发页面切换:
@override Widget build(BuildContext context) { return Scaffold( // 显示当前选中的页面 body: _pages[_currentIndex], bottomNavigationBar: SalomonBottomBar( currentIndex: _currentIndex, onTap: (index) { setState(() { _currentIndex = index; // 更新索引后自动切换页面 }); // 如果需要跳转至非页面栈内的页面,可在此添加Navigator逻辑: // Navigator.push(context, MaterialPageRoute(builder: (context) => TargetPage())); }, items: [ SalomonBottomBarItem( icon: const Icon(Icons.home_outlined), title: const Text("首页"), selectedColor: Colors.blue, ), // 你提供的Likes导航项 SalomonBottomBarItem( icon: const Icon(Icons.favorite_border), title: const Text("Likes"), selectedColor: Colors.pink, ), SalomonBottomBarItem( icon: const Icon(Icons.person_outline), title: const Text("我的"), selectedColor: Colors.purple, ), ], ), ); }
3. 页面状态保持(可选)
如果需要切换页面时保留之前的页面状态(比如输入框内容、滚动位置),将页面容器替换为IndexedStack:
body: IndexedStack( index: _currentIndex, children: _pages, ),
补充说明
salomon_bottom_bar本质是UI组件,不内置路由逻辑,核心思路就是通过点击回调更新状态,再根据状态展示对应页面组件,这也是Flutter底部导航的通用实现方式。
内容的提问来源于stack exchange,提问作者sameh
相关产品推荐
相关产品推荐

