效果:
/**
* Flutter BottomNavigationBar 自定義底部導航條、以及實現頁面切換:
* BottomNavigationBar是底部導航條,可以讓我們定義底部Tab切換,
* bottomNavigationBar是Scaffold組件的參數。
*BottomNavigationBar常見的屬性:
items List<BottomNavigationBaritem> 底部導航條按鈕集合。
iconSize icon
currentIndex 默認選中第幾個
onTap 選中變化回調函數
fixedColor 選中的顏色
type
BottomNavigationBarType.fixed
BottomNavigationBarType.shifting
*/
main.dart
import 'package:flutter/material.dart'; import 'pages/Tabs.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return MaterialApp( home: Tabs(), ); } }
pages/Tabs.dart
import 'package:flutter/material.dart'; import 'tabs/Home.dart'; import 'tabs/Category.dart'; import 'tabs/Setting.dart'; class Tabs extends StatefulWidget { Tabs({Key key}) : super(key: key); _TabsState createState() => _TabsState(); } class _TabsState extends State<Tabs> { int _currentIndex = 0; List _pageList=[ HomePage(), CategoryPage(), SettingPage() ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), bottomNavigationBar: BottomNavigationBar( currentIndex: this._currentIndex, onTap: (int index) { // print(index); setState(() { this._currentIndex = index; }); }, iconSize: 36.0, type: BottomNavigationBarType.fixed, fixedColor: Colors.red, items: [ BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('首頁')), BottomNavigationBarItem( icon: Icon(Icons.category), title: Text('分類')), BottomNavigationBarItem( icon: Icon(Icons.settings), title: Text('設置')), ]), body: this._pageList[this._currentIndex], ); } }
pages/tabs/Home.dart
import 'package:flutter/material.dart'; class HomePage extends StatelessWidget { const HomePage({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Text('首頁'), ); } }
pages/tabs/Category.dart
import 'package:flutter/material.dart'; class CategoryPage extends StatelessWidget { const CategoryPage({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Text('分類') ); } }
pages/tabs/Setting.dart
import 'package:flutter/cupertino.dart'; class SettingPage extends StatelessWidget { const SettingPage({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Text('設置'), ); } }