实现点击以及滑动都可以切换导航的效果
核心代码
完整代码
// 输入 imrm 快速生成下面
import 'package:flutter/material.dart';
import 'Home.dart';
import 'HomeNew.dart';
import 'Category.dart';
import 'User.dart';
import 'Cart.dart';
class Tabs extends StatefulWidget {
const Tabs({Key? key, arguments}) : super(key: key);
@override
_TabsState createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex = 0;
late PageController _pageController; // 缓存页面重要代码
@override
void initState() {
super.initState();
this._pageController =
new PageController(initialPage: this._currentIndex); // 缓存页面重要代码
}
Widget _initPng() {
return Image.asset(
'assets/images/tdd2.png',
height: 25.0,
);
}
static const Color myPink = Color(0xFFdf769e);
var _title;
List<Widget> _pageList = [
HomeNewPage(),
HomePage(),
CategoryPage(),
CartPage(),
UserPage()
];
void _pageChange(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
// _title = _initPng();
return Scaffold(
//这里设置总体背景色
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0, //隐藏底部阴影分割线
centerTitle: true, //标题是否居中 安卓上有效ios默认居中
backgroundColor: Colors.white, //设置导航背景颜色
title: _title,
),
// title: Text('我是title')),
// body: Text('页码下标' + this._currentIndex.toString()),
// body: this._pageList[this._currentIndex],
body: PageView(
onPageChanged: _pageChange,
controller: this._pageController, // 缓存页面重要代码
children: this._pageList,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
BottomNavigationBarItem(icon: Icon(Icons.home), label: '测试'),
BottomNavigationBarItem(icon: Icon(Icons.category), label: '分类'),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), label: '购物车'),
BottomNavigationBarItem(icon: Icon(Icons.people), label: '个人中心'),
],
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
this._currentIndex = index;
this._pageController.jumpToPage(index); // 缓存页面重要代码
switch (index) {
case 0:
{
print('case01');
_title = Image.asset(
'assets/images/tdd2.png',
height: 25.0,
);
}
break;
case 1:
{
_title = Text(
"测试页面",
style: TextStyle(
color: myPink,
fontSize: 17,
letterSpacing: 1,
wordSpacing: 2,
height: 1.2,
fontWeight: FontWeight.w600),
);
}
break;
case 2:
{
_title = Text(
"分类",
style: TextStyle(
color: myPink,
fontSize: 17,
letterSpacing: 1,
wordSpacing: 2,
height: 1.2,
fontWeight: FontWeight.w600),
);
}
break;
case 3:
{
_title = Text(
"购物车",
style: TextStyle(
color: myPink,
fontSize: 17,
letterSpacing: 1,
wordSpacing: 2,
height: 1.2,
fontWeight: FontWeight.w600),
);
}
break;
case 4:
{
_title = Text(
"个人中心",
style: TextStyle(
color: myPink,
fontSize: 17,
letterSpacing: 1,
wordSpacing: 2,
height: 1.2,
fontWeight: FontWeight.w600),
);
}
break;
}
});
},
type: BottomNavigationBarType.fixed,
fixedColor: myPink,
),
);
}
}