实现底部导航栏并点击切换页面可简述为有三种方式 1,BottomNavigationBar 2,自定义 BottomAppBar 3,TabBar + TabBarView

在Flutter应用中,导航栏切换页面后默认情况下会丢失原页面状态,即每次进入页面时都会重新初始化状态,如果在initState中打印日志,会发现每次进入时都会输出,显然这样增加了额外的开销,并且带来了不好的用户体验。

1, 1,BottomNavigationBar + BottomNavigationBarItem(index_page页面)
在这里插入图片描述
2,自定义 BottomAppBar 使用 BottomAppBar 来实现

在这里插入图片描述

3,TabBar + TabBarView
在这里插入图片描述
源码github

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现从其他子页面跳转到TabBar中的某个页面时,不覆盖底部导航栏,你可以使用Flutter中的IndexedStack组件来管理页面堆栈,并在跳转时设置相关参数以实现你的需求。 首先,在你的TabBar页面中,定义一个变量来存储当前选中的页面索引: ```dart int currentIndex = 0; ``` 然后,在TabBarView中使用IndexedStack来管理页面堆栈: ```dart IndexedStack( index: currentIndex, children: [ // 页面1 // 页面2 // 页面3 ], ) ``` 接下来,在底部导航栏中,使用BottomNavigationBar来显示导航按钮,并在点击按钮时更新currentIndex的值: ```dart BottomNavigationBar( currentIndex: currentIndex, onTap: (index) { setState(() { currentIndex = index; }); }, items: [ BottomNavigationBarItem( icon: Icon(Icons.page1), label: 'Page 1', ), BottomNavigationBarItem( icon: Icon(Icons.page2), label: 'Page 2', ), BottomNavigationBarItem( icon: Icon(Icons.page3), label: 'Page 3', ), ], ) ``` 这样,通过点击底部导航栏上的按钮,可以在TabBarView切换到对应的页面,且底部导航栏始终保持可见。 接下来,在其他子页面中,通过Navigator组件进行跳转到TabBar页面的某个页面时,可以使用Navigator.pushReplacement方法替换当前路由,并将currentIndex参数传递过去: ```dart Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => TabBarPage(currentIndex: desiredIndex), ), ); ``` 在TabBarPage中,接收currentIndex参数,并在初始化时将其赋值给currentIndex变量: ```dart class TabBarPage extends StatefulWidget { final int currentIndex; TabBarPage({this.currentIndex = 0}); @override _TabBarPageState createState() => _TabBarPageState(); } class _TabBarPageState extends State<TabBarPage> { int currentIndex; @override void initState() { super.initState(); currentIndex = widget.currentIndex; } @override Widget build(BuildContext context) { return Scaffold( // TabBarTabBarView实现 // ... ); } } ``` 这样,在从其他子页面跳转到TabBar中的某个页面时,底部导航栏不会被覆盖,并且保持正确的页面索引。 希望以上代码示例能帮到你!如果还有其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值