2分钟
05 Tabbar控件实现-3
每个 Tab 对应的 StatefulWidget
的 State ,需要通过with AutomaticKeepAliveClientMixin
,然后重写 @override bool get wantKeepAlive => true;
,就可以实不重新构建的效果了,效果如下图。
既然底部Tab页面都实现了,干脆顶部tab页面也一起完成。如下代码,和底部Tab页的区别在于:
- 底部tab是放在了
Scaffold
的bottomNavigationBar
中。 - 顶部tab是放在
AppBar
的bottom
中,也就是标题栏之下。
同时我们在顶部 TabBar 增加 isScrollable: true
属性,实现常见的顶部Tab的效果,如下方图片所示。
return new Scaffold(
///设置侧边滑出 drawer,不需要可以不设置
drawer: _drawer,
///设置悬浮按键,不需要可以不设置
floatingActionButton: _floatingActionButton,
///标题栏
appBar: new AppBar(
backgroundColor: _backgroundColor,
title: _title,
///tabBar控件
bottom: new TabBar(
///顶部时,tabBar为可以滑动的模式
isScrollable: true,
///必须有的控制器,与pageView的控制器同步
controller: _tabController,
///每一个tab item,是一个List<Widget>
tabs: _tabItems,
///tab底部选中条颜色
indicatorColor: _indicatorColor,
),
),
///页面主体,PageView,用于承载Tab对应的页面
body: new PageView(
///必须有的控制器,与tabBar的控制器同步
controller: _pageController,
///每一个 tab 对应的页面主体,是一个List<Widget>
children: _tabViews,
///页面触摸作用滑动回调,用于同步tab选中状态
onPageChanged: (index) {
_tabController.animateTo(index);
},
),
);
在 TabBar 页面中,一般还会出现:父页面需要控制 PageView 中子页的需求,这时候就需要用到GlobalKey
了,比如 GlobalKey stateOne = new GlobalKey();
,通过 globalKey.currentState 对象,你就可以调用到 PageOneState 中的公开方法,这里需要注意 GlobalKey
实例需要全局唯一。
学员评价