Flutter创建底部导航的方式:推荐第三种
一、BottomNavigationBar
+ BottomNavigationBarItem
- 优缺点:
- 实现简单,代码量很少基本就能完成
- 不能调整
item
的文字和图片间距 - 每次切换页面会重绘,不会保存之前的页面状态
具体实现:
///根页面
class MainPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return MainPageState();
}
}
class MainPageState extends State <MainPage> {
int currentIndex = 0;
final items = [
BottomNavigationBarItem(icon: Image(image: AssetImage('images/Home.png')), title: Text
('首页'),activeIcon: Image(image:
AssetImage
('images/HomeSelect'
'.png'))),
BottomNavigationBarItem(icon: Image(image: AssetImage('images/market_normal.png')),
title:
Text("行情"),activeIcon: Image(image: AssetImage('images/market_selected.png'))),
BottomNavigationBarItem(icon: Image(image: AssetImage('images/transcation_normal.png')),
title: Text
("交易"),activeIcon: Image
(image:
AssetImage('images/transcation_selected.png'),)),
BottomNavigationBarItem(icon: Image(image: AssetImage('images/assets_normal.png')),
title: Text
("资产"),activeIcon: Image(image:
AssetImage('images/assets_selected.png'),)),
];
///4个tabbar页面
final bodyLists = [
HomepageWidget(),
MarketpageWidget(),
TranscationpageWidget(),
AssetspageWidget()
];
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold (
appBar: AppBar(title: Text("切换"),),
bottomNavigationBar: BottomNavigationBar(
items: items,
currentIndex: currentIndex,
onTap: onTap,
unselectedItemColor: prefix1.Color(0xFF989D9D),
selectedItemColor: prefix1.Color(0xFF333333),
type: BottomNavigationBarType.fixed,
),
body: bodyLists[currentIndex],
);
}
void onTap(int index) {
setState(() {
currentIndex = index;
});
}
}
每个子页面代码都是一样的,主要是为了测试每个页面的状态
import 'package:flutter/material.dart';
class HomepageWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return HomepageWidgetState();
}
}
class HomepageWidgetState extends State <HomepageWidget> {
int count = 0;
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: Center(
child: Text("首页 $count",style: TextStyle(color: Colors.blue),),
),
floatingActionButton: FloatingActionButton(
onPressed: addButtonClick,
child: Icon(Icons.add),
),
);
}
void addButtonClick() {
setState(() {
count ++;
});
}
}
如上图,我们可以看到当切换界面的时候,之前的状态是被重置了的。那么下面介绍该如何保持状态。
二、BottomNavigationBar
+Stack
+ OffStage
- 优缺点
- 能够保存页面的状态
- 程序初始化的时候所有的
child
都会执行initState
(有时候我们想要的效果是当点击tabbar
的时候界面再去加载) - 使用
BottomNavigationBarItem
无法调整文字图片间距
body: Stack(
children: [
_stackOffstage(0),
_stackOffstage(1),
_stackOffstage(2),
_stackOffstage(3)
],
),
//根据点击的索引返回widget
Widget _stackOffstage(int index) {
return Offstage(
//If false, the child is included in the tree as normal.
offstage: currentIndex != index,
child: TickerMode(
child: bodyLists[index],
//If true, then tickers in this subtree will tick.
enabled: currentIndex == index,
),
);
}
三、使用PageView
+ AutomaticKeepAliveClientMixin
- 优点
- 可以保存页面状态
- 每次点击才会初始化,而且只会初始化一次
-
push pop
回来widgetState
也不会重新initState
var pageController = PageController();
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold (
appBar: AppBar(title: Text("切换"),),
bottomNavigationBar: BottomNavigationBar(
items: items,
currentIndex: currentIndex,
onTap: onTap,
unselectedItemColor: prefix1.Color(0xFF989D9D),
selectedItemColor: prefix1.Color(0xFF333333),
type: BottomNavigationBarType.fixed,
),
body: PageView(
controller: pageController,
children: bodyLists,
onPageChanged:pageControllerTap ,
physics: NeverScrollableScrollPhysics(),
),
);
}
void pageControllerTap(int index) {
setState(() {
currentIndex = index;
});
}
void onTap(int index) {
pageController.jumpToPage(index);
}
其中子页面的代码,需要注意 AutomaticKeepAliveClientMixin
, 重写方法
wantKeepAlive
,这样是让页面一直保存在内存中。还有一个要注意的点:super.build(context);
,如果不写,当我们使用Navigator.push
切换界面的时候,再pop
回来,HomepageWidgetState
还是会执行initState
,加上super
后就不会再有这个问题。
class HomepageWidgetState extends State <HomepageWidget> with AutomaticKeepAliveClientMixin {
@override
void initState() {
// TODO: implement initState
super.initState();
print('HomepageWidgetState initState');
}
int count = 0;
@override
Widget build(BuildContext context) {
// TODO: implement build
super.build(context); //注意:每个子页面要写`super`
return Scaffold(
body: Center(
child: Text("首页 $count",style: TextStyle(color: Colors.blue),),
),
floatingActionButton: FloatingActionButton(
onPressed: addButtonClick,
child: Icon(Icons.add),
),
);
}
void addButtonClick() {
setState(() {
count ++;
});
}
//一直保存在内存中
@override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
其中PageController
是可以控制pageView
中要显示的界面
physics
//How the page view should respond to user input. 用户如何响应,具体行为可以查看源码,我们这里可以禁止滑动NeverScrollableScrollPhysics
[ScrollPhysics], which can be used instead of this class when the default
/// behavior is desired instead.
/// * [BouncingScrollPhysics], which provides the bouncing overscroll behavior
/// found on iOS.
/// * [ClampingScrollPhysics], which provides the clamping overscroll behavior
/// found on Android.