直接看代码案例快速入手Flutter
本文介绍BottomNavigationBar, TabBar, Navigator.
BottomNavigationBar是底部导航栏,类似与iOS中的UITabViewController, Navigator可以处理页面之间的导航,TabBar一般用于次级导航栏,也可以作为底部导航栏。
🎉下载GitHub仓库,直接体验
BottomNavigationBar
Scaffold(
appBar: AppBar(
title: Text(
"${runtimeType.toString().substring(0, runtimeType.toString().length - 9)} Example"),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Hello, Flutter! $_selectedIndex'),
],
),
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
Navigator
// 直接跳转进TextPage
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const RichTextPage()),
);
// 传递一个字符参数和闭包给TextPage
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TextPage(
text: 'Example Text',
onTextChange: (String newText) {
debugPrint('Text changed: $newText');
},
)),
);
TabBar
// 显示在顶部的TabBar
Scaffold(
appBar: AppBar(
title: const Text('DefaultTabController Example'),
bottom: const TabBar(
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
body: const TabBarView(
children: [
Center(child: Text('Tab 1 Content')),
Center(child: Text('Tab 2 Content')),
Center(child: Text('Tab 3 Content')),
],
),
),
// 显示在底部的TabBar
Scaffold(
appBar: AppBar(
title: const Text('DefaultTabController Example'),
),
body: const TabBarView(
children: [
Center(child: Text('Tab 1 Content')),
Center(child: Text('Tab 2 Content')),
Center(child: Text('Tab 3 Content')),
],
),
bottomNavigationBar: Container(
color: Theme.of(context).primaryColor, // 设置与 AppBar 相同的背景色
child: const SafeArea(
child: SizedBox(
height: kToolbarHeight, // 设置标准工具栏高度
child: TabBar(
tabs: [
Tab(icon: Icon(Icons.home), text: 'Tab 1'),
Tab(icon: Icon(Icons.star), text: 'Tab 2'),
Tab(icon: Icon(Icons.settings), text: 'Tab 3'),
],
),
),
),
),
)