class MessagePage extends StatefulWidget {
@override
_MessagePageState createState() => _MessagePageState();
}
class _MessagePageState extends State<MessagePage> with AutomaticKeepAliveClientMixin<MessagePage> {
...
}
class _MessagePageState extends State<MessagePage> with AutomaticKeepAliveClientMixin<MessagePage> {
...
@override
bool get wantKeepAlive => true;
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(...);
}
class _MyHomePageDataSource extends State<MyHomePage> {
int _selectedTab = 0;
final List<Widget> _pages = [
MessagePage(),
ContactsPage(),
MommentPage(),
MinePage()
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_selectedTab],
...
);
class _MyHomePageDataSource extends State<MyHomePage> {
int _selectedTab = 0;
final List<Widget> _pages = [
MessagePage(),
ContactsPage(),
MommentPage(),
MinePage()
];
// 一、 构建 PageController
final PageController _pageController = PageController();
@override
Widget build(BuildContext context) {
return Scaffold(
// 二、 调整 Body 为 PageView, 并绑定 PageController 和 pages
body: PageView(
controller: _pageController,
children: _pages,
),
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
currentIndex: _selectedTab,
onTap: (idx) {
setState(() {
_selectedTab = idx;
// 三、 通过 PageController 切换子页面
_pageController.jumpToPage(_selectedTab);
});
},
items: const [...],
),
);
}
}
body: PageView(
onPageChanged: (idx) {
setState(() {
_selectedTab = idx;
});
},
controller: _pageController,
children: _pages,
),
body: PageView(
physics: const NeverScrollableScrollPhysics(),
controller: _pageController,
children: _pages,
),