MaterialApp风格实现
思路:PageView
+ BottomNavigationBar
PageView
存放tabbar管理的子页面。
BottomNavigationBar
负责tabbar展示及页面切换事件。
- 创建StatefulWidget
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
@override
Widget build(BuildContext context) {
return Container();
}
}
- 声明_pages和_barItems
/*页面索引*/
int _currentIndex = 0;
/*页面*/
List _pages = [HomeView(),MyView()];
/*页面控制器*/
final _pageController = PageController();
/*tabbarItems*/
List _barItems = [
BottomNavigationBarItem(label: '首页', icon: Image.asset('images/tabbar_icon_house_normal.png'), activeIcon: Image.asset('images/tabbar_icon_house_selected.png')),
BottomNavigationBarItem(label: '我的', icon: Image.asset('images/tabbar_icon_my_normal.png'), activeIcon: Image.asset('images/tabbar_icon_my_selected.png')),
];
- 实现
/*声明_pages和_barItems*/
...
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'my app',
home: Scaffold(
body: PageView.builder(
physics: NeverScrollableScrollPhysics(),
controller: _pageController,
onPageChanged: (int index) {
setState(() {
_currentIndex = index;
});
},
itemBuilder: (context, index) {
return _pages[index];
},
),
bottomNavigationBar: BottomNavigationBar(
items: _barItems,
currentIndex: _currentIndex,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
selectedFontSize: 12,
unselectedFontSize: 12,
onTap: (int index) {
_pageController.jumpToPage(index);
},
),
),
);
}
- 清理
@override
void dispose() {
super.dispose();
_pageController.dispose();
}
实际使用时,应将此实现封装到一个dart文件中,方便维护。
效果
CupertinoApp风格实现
@override
Widget build(BuildContext context) {
return CupertinoApp(
title: 'my app',
home: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: _barItems,
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
),
tabBuilder: (context, index) {
return _pages[index];
},
),
);
}
对应的CupertinoPageScaffold
页面
class HomeView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('首页'),
),
child: Container(
child: Text('文本'),
),
);
}
}
效果