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 Color? titleColor; final Color? backIconColor; final double? elevation; final bool? showBackButton; const CustomAppBarWidget({ super.key, required this.title, this.actions, this.leading, this.centerTitle = true, this.backgroundColor = Colors.white, this.titleColor = Colors.black, this.backIconColor = Colors.black, this.elevation, this.showBackButton = true, }); @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, color: titleColor, ), ), actions: actions, automaticallyImplyLeading: this.showBackButton ?? true, // 根据是否有自定义leading来决定使用什么 leading: leading ?? (showBackButton && this.showBackButton == true ? IconButton( icon: Icon( Icons.arrow_back_ios_new_rounded, color: backIconColor, ), onPressed: () => Navigator.of(context).pop(), ) : null), // 当有leading时标题默认左对齐,否则按centerTitle参数决定 centerTitle: false, backgroundColor: backgroundColor, elevation: elevation, ); } @override Size get preferredSize => const Size.fromHeight(kToolbarHeight); }