hi_navigator.dart
添加首页底部Tab切换监听
// 首页底部tab
RouteStatusInfo _bottomTab;
// 首页底部 tab 切换监听
void addBottomTabChange(int index, Widget page) {
_bottomTab = RouteStatusInfo(RouteStatus.home, page);
_notify(_bottomTab);
}
void _notify(RouteStatusInfo current) {
if (current is BottomNavigator && _bottomTab != null) {
// 如果打开的是首页,则明确到首页具体的tab
current = _bottomTab;
}
_listeners.forEach((element) {
element(current, _current);
});
_current = current;
}
bottom_navigator.dart
封装 PageView 和 BottomNavigationBar 切换监听,动态设置 底部 tab 切换监听
static int initialPage = 0;
final PageController _controller = new PageController(initialPage: initialPage);
@override
Widget build(BuildContext context) {
_pages = [HomePage(), HomePage(), HomePage(), HomePage()];
if (!_hasBuild) {
// 页面第一次打开时通知打开的是哪个tab
HiNavigator.getInstance()
.addBottomTabChange(initialPage, _pages[initialPage]);
_hasBuild = true;
}
return Scaffold(
body: PageView(
controller: _controller,
children: _pages,
onPageChanged: (index) => _onJumpTo(index, pageChange: true),
physics: NeverScrollableScrollPhysics(), // 禁止 PageView 滑动
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) => _onJumpTo(index),
selectedItemColor: _activeColor,
items: [
_bottomItem('首页', Icons.home, 0),
_bottomItem('排行', Icons.local_fire_department, 1),
_bottomItem('收藏', Icons.favorite, 2),
_bottomItem('我的', Icons.live_tv, 3),
],
type: BottomNavigationBarType.fixed, // 设置未选中也能显示标题
),
);
}
void _onJumpTo(int index, {pageChange = false}) {
if (!pageChange) {
// 让PageView展示对应tab
_controller.jumpToPage(index);
} else {
HiNavigator.getInstance().addBottomTabChange(index, _pages[index]);
}
setState(() {
_currentIndex = index;
});
}
home_page.dart
防止页面重新初始化
class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
}