一,代码:
tabbar:
import 'package:flutter/material.dart';
import '../tabpages/MyHomePage.dart';
import '../tabpages/ProfilePage.dart';class MyTabBar extends StatefulWidget {const MyTabBar({super.key});@overrideState<MyTabBar> createState() => _MyTabBarState();
}class _MyTabBarState extends State<MyTabBar>with SingleTickerProviderStateMixin {final List<Widget> pages = const [MyHomePage(), ProfilePage()];/// PageView 控制器 , 用于控制 PageViewlate PageController _pageController;int _currentIndex = 0;@overridevoid initState() {super.initState();_pageController = PageController(/// 初始索引值initialPage: 0,);}@overridevoid dispose() {super.dispose();/// 销毁 PageView 控制器_pageController.dispose();}@overrideWidget 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});@overrideState<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin {@overrideWidget 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内容"),),);}@overridebool get wantKeepAlive => true;
}
第二个页面:
import 'package:flutter/material.dart';class ProfilePage extends StatefulWidget {const ProfilePage({super.key});@overrideState<ProfilePage> createState() => _ProfilePageState();
}class _ProfilePageState extends State<ProfilePage> with AutomaticKeepAliveClientMixin{@overrideWidget 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内容"),),);}@overridebool get wantKeepAlive => true;
}