custom_app_bar.dart 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import 'package:flutter/material.dart';
  2. import 'package:go_router/go_router.dart';
  3. class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  4. final String title;
  5. final bool showBackButton;
  6. final List<Widget>? actions;
  7. final VoidCallback? onBack;
  8. const CustomAppBar({
  9. super.key,
  10. required this.title,
  11. this.showBackButton = true,
  12. this.actions,
  13. this.onBack,
  14. });
  15. @override
  16. Widget build(BuildContext context) {
  17. return AppBar(
  18. title: Text(title),
  19. centerTitle: true,
  20. leading: showBackButton
  21. ? IconButton(
  22. icon: const Icon(Icons.arrow_back),
  23. onPressed: () {
  24. if (onBack != null) {
  25. onBack!();
  26. } else if (context.canPop()) {
  27. // 如果可以返回,则返回上一页
  28. context.pop();
  29. } else {
  30. // 如果无法返回,则导航到首页
  31. context.go('/');
  32. }
  33. },
  34. )
  35. : null,
  36. actions: actions,
  37. );
  38. }
  39. @override
  40. Size get preferredSize => const Size.fromHeight(kToolbarHeight);
  41. }