import 'dart:async'; import 'package:flutter/material.dart'; import 'package:lszlgl/base/base_state.dart'; import 'package:lszlgl/page/home/home_page.dart'; import 'package:lszlgl/page/user_center/user_center_page.dart'; /// 主页tab页面 class MainTabPage extends StatefulWidget { const MainTabPage({Key? key}) : super(key: key); @override State createState() => _MainTabPageState(); } class _MainTabPageState extends State { late List tabTextList; late List tabIconList; late List tabIconSelectList; late List pageList; late PageController ctrl; int selectedIndex = 0; DateTime? lastTime; ValueNotifier popState = ValueNotifier(false); void refreshTab(int index, {bool refreshPage = false}) { if (index == selectedIndex) return; setState(() { selectedIndex = index; }); if (refreshPage) ctrl.jumpToPage(index); } @override void initState() { super.initState(); tabTextList = ['首页', '用户中心']; tabIconList = [imgNavHome, imgNavUserCenter]; tabIconSelectList = [imgNavHomeSelect, imgNavUserCenterSelect]; pageList = [const HomePage(), const UserCenterPage()]; ctrl = PageController(initialPage: selectedIndex); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF3F3F3), body: buildPop(buildBody()), bottomNavigationBar: buildNavigation(), ); } Widget buildPop(Widget child) { return ValueListenableBuilder( valueListenable: popState, builder: (_, value, __) { return PopScope( canPop: value, child: child, onPopInvoked: (didPop) { if (didPop) return; MyNavigator.showToast('再试一次退出'); popState.value = true; // 2秒后不可退出 Timer( const Duration(seconds: 2), () => popState.value = false, ); }, ); }, ); } Widget buildBody() { return PageView.builder( controller: ctrl, // physics: const BouncingScrollPhysics(), onPageChanged: refreshTab, itemCount: pageList.length, itemBuilder: (_, index) => pageList[index], ); } Widget buildNavigation() { return NavigationBar( height: 56, selectedIndex: selectedIndex, surfaceTintColor: Colors.white, onDestinationSelected: (index) => refreshTab(index, refreshPage: true), backgroundColor: Colors.white, destinations: List.generate( tabTextList.length, (index) => GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => refreshTab(index, refreshPage: true), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset( index == selectedIndex ? tabIconSelectList[index] : tabIconList[index], height: 18, ), Text( tabTextList[index], style: TextStyle( fontSize: 12, fontWeight: FontWeight.w500, color: index == selectedIndex ? const Color(0xFF333333) : const Color(0xFF888888), ), ), ], ), ), ).toList(), ); } }