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

bottom_nav_bar.dart 2.3KB

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