这是CaiYouHui前端,一个关于flutter的安卓app,前端使用flutter实现

bottom_nav_bar.dart 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import 'package:flutter/material.dart';
  2. import 'package:provider/provider.dart';
  3. import '../../core/constants/route_constants.dart';
  4. import '../../presentation/providers/auth_provider.dart';
  5. class BottomNavBar extends StatefulWidget {
  6. final int initialIndex;
  7. const BottomNavBar({
  8. super.key,
  9. this.initialIndex = 0,
  10. });
  11. @override
  12. State<BottomNavBar> createState() => _BottomNavBarState();
  13. }
  14. class _BottomNavBarState extends State<BottomNavBar> {
  15. int _selectedIndex = 0;
  16. @override
  17. void initState() {
  18. super.initState();
  19. _selectedIndex = widget.initialIndex;
  20. }
  21. void _onItemTapped(int index) {
  22. final authProvider = Provider.of<AuthProvider>(context, listen: false);
  23. // 如果点击"我的"但未登录,跳转到登录页
  24. if (index == 3 && !authProvider.isAuthenticated) {
  25. Navigator.of(context).pushNamed(RouteConstants.login);
  26. return;
  27. }
  28. setState(() {
  29. _selectedIndex = index;
  30. });
  31. switch (index) {
  32. case 0:
  33. if (ModalRoute.of(context)?.settings.name != RouteConstants.home) {
  34. Navigator.of(context).pushReplacementNamed(RouteConstants.home);
  35. }
  36. break;
  37. case 1:
  38. if (ModalRoute.of(context)?.settings.name != RouteConstants.news) {
  39. Navigator.of(context).pushReplacementNamed(RouteConstants.news);
  40. }
  41. break;
  42. case 2:
  43. if (ModalRoute.of(context)?.settings.name != RouteConstants.services) {
  44. Navigator.of(context).pushReplacementNamed(RouteConstants.services);
  45. }
  46. break;
  47. case 3:
  48. if (ModalRoute.of(context)?.settings.name != RouteConstants.profile) {
  49. Navigator.of(context).pushReplacementNamed(RouteConstants.profile);
  50. }
  51. break;
  52. }
  53. }
  54. @override
  55. Widget build(BuildContext context) {
  56. return BottomNavigationBar(
  57. items: const [
  58. BottomNavigationBarItem(
  59. icon: Icon(Icons.home_outlined),
  60. activeIcon: Icon(Icons.home),
  61. label: '首页',
  62. ),
  63. BottomNavigationBarItem(
  64. icon: Icon(Icons.newspaper_outlined),
  65. activeIcon: Icon(Icons.newspaper),
  66. label: '资讯',
  67. ),
  68. BottomNavigationBarItem(
  69. icon: Icon(Icons.work_outline),
  70. activeIcon: Icon(Icons.work),
  71. label: '服务',
  72. ),
  73. BottomNavigationBarItem(
  74. icon: Icon(Icons.person_outline),
  75. activeIcon: Icon(Icons.person),
  76. label: '我的',
  77. ),
  78. ],
  79. currentIndex: _selectedIndex,
  80. selectedItemColor: Theme.of(context).primaryColor,
  81. unselectedItemColor: Colors.grey,
  82. showUnselectedLabels: true,
  83. type: BottomNavigationBarType.fixed,
  84. onTap: _onItemTapped,
  85. );
  86. }
  87. }