Flutter有三种导航:抽屉导航(Drawer),底部导航(BottomNavigation),普通导航(TabBar)
底部导航
import 'package:flutter/material.dart';
class Nav extends StatefulWidget {
const Nav({Key? key}) : super(key: key);
@override
State<Nav> createState() => _NavState();
}
class _NavState extends State<Nav> {
// 导航菜单
List<BottomNavigationBarItem> bottomNav = [
const BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
const BottomNavigationBarItem(icon: Icon(Icons.message), label: "消息"),
const BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), label: "购物车"),
const BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
];
// 导航页面
List<Widget> pages = [
const Center(child: Text("Home", style: TextStyle(fontSize: 50),),),
const Center(child: Text("Message", style: TextStyle(fontSize: 50),),),
const Center(child: Text("Cart", style: TextStyle(fontSize: 50),),),
const Center(child: Text("Profile", style: TextStyle(fontSize: 50),),),
];
int idx = 0;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: bottomNav,
currentIndex: idx,
type: BottomNavigationBarType.fixed,
onTap: (index) {
_changePage(index);
},
),
body: pages[idx],
),
);
}
_changePage(int index) {
if(idx != index) {
setState(() {
idx = index;
});
}
}
}