import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class CustomAppBarWidget extends StatelessWidget implements PreferredSizeWidget { final String title; final List? actions; final Widget? leading; final bool centerTitle; final Color? backgroundColor; final double? elevation; const CustomAppBarWidget({ super.key, required this.title, this.actions, this.leading, this.centerTitle = true, this.backgroundColor = Colors.white, this.elevation, }); @override Widget build(BuildContext context) { // 判断是否需要显示返回按钮 bool showBackButton = ModalRoute.of(context)?.canPop ?? false; return AppBar( title: Text( title, style: TextStyle( fontSize: 18.sp, fontWeight: FontWeight.w500, ), ), actions: actions, // 根据是否有自定义leading来决定使用什么 leading: leading ?? (showBackButton ? IconButton( icon: const Icon(Icons.arrow_back_ios_new_rounded), onPressed: () => Navigator.of(context).pop(), ) : null), // 当有leading时标题默认左对齐,否则按centerTitle参数决定 centerTitle: false, backgroundColor: backgroundColor, elevation: elevation, ); } @override Size get preferredSize => const Size.fromHeight(kToolbarHeight); }