Flutter Material3风格 导航栏

源码下载

Material Doc

main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'package:flutter/material.dart';
import 'package:navbar_01/homepage.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage());
}
}
homepage.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
State<HomePage> createState() => _HomePageState();
}

const TextStyle _textStyle = TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
letterSpacing: 2,
);

class _HomePageState extends State<HomePage> {
// 当前页面索引
int _currentIndex = 0;

// 页面列表
final List<Widget> _pages = [
const Text("eco", style: _textStyle),
const Text("home", style: _textStyle),
const Text("person", style: _textStyle),
const Text("video", style: _textStyle),
];

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _pages[_currentIndex],
),
// 导航栏
// 可以不使用 NavigationBarTheme ,只单独使用 NavigationBar
bottomNavigationBar: NavigationBarTheme(
data: NavigationBarThemeData(
// 指示器,作用于导航图标上
indicatorColor: Colors.teal.withOpacity(0.2),
// 作用与label上的样式
labelTextStyle: MaterialStateProperty.all(
const TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
backgroundColor: Colors.grey.withOpacity(0.2),
),
child: NavigationBar(
// 导航栏背景色 优先级大于 NavigationBarThemeData 中的 backgroundColor
// backgroundColor: Colors.teal,
// 动画时长
animationDuration: const Duration(seconds: 1),
// 是否显示label
// alwaysHide 不显示label
// alwaysShow 一直显示label
// onlyShowSelected 只显示激活项的label
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
// 导航栏高度
height: 60,
// 当前选择项的索引
selectedIndex: _currentIndex,
// 选择项目后触发的事件
onDestinationSelected: (int newIndex) {
setState(() {
_currentIndex = newIndex;
});
},
// 每个导航项目对应的内容,最少2个
destinations: const [
NavigationDestination(
icon: Icon(Icons.eco_outlined),
selectedIcon: Icon(Icons.eco),
label: "eco",
),
NavigationDestination(
icon: Icon(Icons.home_outlined),
selectedIcon: Icon(Icons.home),
label: "home",
),
NavigationDestination(
icon: Icon(Icons.person_outline),
selectedIcon: Icon(Icons.person),
label: "person",
),
NavigationDestination(
icon: Icon(Icons.video_camera_back_outlined),
selectedIcon: Icon(Icons.video_camera_back),
label: "video",
),
],
),
),
);
}
}