一,代码:
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()];late TabController _tabController;int _currentIndex = 0;@overridevoid initState() {super.initState();_tabController = TabController(length: pages.length, vsync: this);//去掉切换页面的动画 Duration.zero// _tabController = TabController(length: pages.length, animationDuration: Duration.zero, vsync: this);}@overrideWidget build(BuildContext context) {return Scaffold(body: TabBarView(controller: _tabController,physics: const NeverScrollableScrollPhysics(),children: pages),bottomNavigationBar: BottomNavigationBar(currentIndex: _currentIndex,selectedItemColor: Colors.red,onTap: (index) {setState(() {_tabController.index = index;_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 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;
}
二,效果: