Flutter:底部導航列換頁(Bottom Navigation)
How to use Flutter to build an app with bottom navigation
6 min readSep 7, 2019
Step 1. 定義進入點
開啟lib/main.dart
。刪除所有程式碼,在首行寫下:
import 'package:flutter/material.dart';
新增Main方法:
void main() => runApp(App());
添加以下方法
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Flutter App',
home: Home(),
);
}
}
上面程式新增了叫作 App
的stateless widget。
並且設定home
作為APP的首頁屬性,我們設定 Home
作為首個出現的畫面
Step 2. 建立home頁面
在 lib
資料夾中,新增home_widget.dart
import 'package:flutter/material.dart';class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0, // this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.mail),
title: new Text('Messages'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
Title: Text('Profile')
)
],
),
);
}
}
回到main.dart,在第二行寫下:
import 'home_widget.dart';
APP目前的樣子:
Step 3. 準備Navigation
回到 home_widget.dart
:
class _HomeState extends State<Home> {
int _currentIndex = 0;
final List<Widget> _children = [];
...@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
body: _children[_currentIndex], // new
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped, // new
currentIndex: _currentIndex, // new
items: [
new BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Messages'),
),
new BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Profile')
)
],
),
);
}
新增的程式用// new
來表示
Step 4. 處理 navigation
在_HomeState
的底部新增以下內容:
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Step 5. 新增child widgets
在lib資料夾中新增placeholder_widget.dart
. 這個檔案負責管理背景顏色(以展示我們確實切換到不同的頁面。
import 'package:flutter/material.dart';
class PlaceholderWidget extends StatelessWidget {
final Color color;
PlaceholderWidget(this.color);
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
回到 home_widget.dart
新增以下內容:
import 'placeholder_widget.dart';
在 _children
中新增下面list內容
class _HomeState extends State<Home> {
int _currentIndex = 0;
final List<Widget> _children = [
PlaceholderWidget(Colors.white),
PlaceholderWidget(Colors.deepOrange),
PlaceholderWidget(Colors.green)
];
...