flutter:bottomNavigationBar+PageView切换页面,使页面可以滑动切换
一,代码:
tabbar:
import 'package:flutter/material.dart';
import '../tabpages/MyHomePage.dart';
import '../tabpages/ProfilePage.dart';
class MyTabBar extends StatefulWidget {
const MyTabBar({super.key});
@override
State<MyTabBar> createState() => _MyTabBarState();
}
class _MyTabBarState extends State<MyTabBar>
with SingleTickerProviderStateMixin {
final List<Widget> pages = const [MyHomePage(), ProfilePage()];
/// PageView 控制器 , 用于控制 PageView
late PageController _pageController;
int _currentIndex = 0;
@override
void initState() {
super.initState();
_pageController = PageController(
/// 初始索引值
initialPage: 0,
);
}
@override
void dispose() {
super.dispose();
/// 销毁 PageView 控制器
_pageController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
/// 滑动组件 , 界面的核心元素
body: PageView(
/// 控制跳转翻页的控制器
controller: _pageController,
/// 页面滑动
/// 这里设置 PageView 页面也能滑动
onPageChanged: (index) {
setState(() {
// 更新当前的索引值
_currentIndex = index;
});
},
/// Widget 组件数组 , 设置多个 Widget 组件
/// 同一时间只显示一个页面组件
children: pages,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
selectedItemColor: Colors.red,
onTap: (index) {
setState(() {
//_pageController.jumpToPage(index);
_pageController.animateToPage(
index,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
_currentIndex = index;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
);
}
}
第一个页面:
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
print("Home build");
super.build(context);
return Scaffold(
appBar: AppBar(
title: const Text(
"Home标题",
style: TextStyle(color: Colors.white),
),
centerTitle: true,
backgroundColor: Colors.blue,
),
body: const Center(
child: Text("Home内容"),
),
);
}
@override
bool get wantKeepAlive => true;
}
第二个页面:
import 'package:flutter/material.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> with AutomaticKeepAliveClientMixin{
@override
Widget build(BuildContext context) {
print("Profile build");
super.build(context);
return Scaffold(
appBar: AppBar(
title: const Text(
"Profile标题",
style: TextStyle(color: Colors.white),
),
centerTitle: true,
backgroundColor: Colors.blue,
),
body: const Center(
child: Text("Profile内容"),
),
);
}
@override
bool get wantKeepAlive => true;
}
二,效果:

浙公网安备 33010602011771号