版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/RedKeyer/article/details/89841723
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: BottomSetState(),
theme: ThemeData(
primarySwatch: Colors.deepPurple, //主题背景颜色
highlightColor: Colors.purple, //按下按钮时 高亮颜色
splashColor: Colors.white30,
),
);
}
}
// 底部导航栏,动态切换选中状态,使用StatefulWidget
class BottomSetState extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _BottomNavigationState();
}
}
// 加载标签 和 对应页面
class _BottomNavigationState extends State<BottomSetState> {
//默认选中 0,_currentIndex当前选中
int _currentIndex = 0;
//定义List用于存储对应页面
List<Widget> listLay = List();
@override
void initState() {
//加载 定义的页面 按顺序,从左到右,对应底部导航栏页签
listLay
..add(_layoutTab(Colors.redAccent, '第1个页面'))
..add(_layoutTab(Colors.greenAccent, '第2个页面'))
..add(_layoutTab(Colors.blueAccent, '第3个页面'))
..add(_layoutTab(Colors.purpleAccent, '第4个页面'));
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70, //页面背景颜色
appBar: AppBar(
// title 中间
title: Text('RedKey',
style: TextStyle(
color: Colors.redAccent,
)),
),
body: listLay[_currentIndex],
// 创建底部导航栏
bottomNavigationBar: BottomNavigationBar(
// items的标签数大于三个,需要重新设定type
type: BottomNavigationBarType.fixed,
// 第几个标签被激活,默认0
currentIndex: _currentIndex,
// 切换激活状态,_onTapHandle是回调监听方法
onTap: _onTapHandle,
// 激活状态的颜色
fixedColor: Colors.orangeAccent,
// items代码从上到下 对应 设备从左到右
items: [
BottomNavigationBarItem(
icon: Icon(Icons.data_usage), //图标
title: Text('data_usage') //文字
),
BottomNavigationBarItem(
icon: Icon(Icons.edit_location), title: Text('edit_location')),
BottomNavigationBarItem(
icon: Icon(Icons.fast_forward), title: Text('fast_forward')),
BottomNavigationBarItem(
icon: Icon(Icons.list), title: Text('List')),
],
));
}
//切换激活状态,_onTapHandle是回调监听方法
void _onTapHandle(int index) {
setState(() {
_currentIndex = index;
});
}
}
//模拟一个通用的页面,包含背景颜色和居中文字
class _layoutTab extends StatelessWidget {
Color _currentColor = Colors.yellow;
String str = '默认页面';
_layoutTab(Color color, String str) {
_currentColor = color;
this.str = str;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
// color: _currentColor,
body: new Container(
color: _currentColor,
child: Center(
child: Text(str,style: TextStyle(fontSize: 38,color: Colors.black),),
),
),
);
}
}
预览效果:
底部导航栏的切换非常流畅