import 'package:flutter/material.dart'; import 'dart:io' show Platform; class MyAppbar extends StatelessWidget implements PreferredSizeWidget { final String title; final VoidCallback? onBackPressed; final Color backgroundColor; final Color textColor; final List? actions; final bool isBack; final bool centerTitle; // 新增:控制标题是否居中 const MyAppbar({ Key? key, required this.title, this.onBackPressed, this.backgroundColor = Colors.blue, this.textColor = Colors.white, this.actions, this.isBack = true, this.centerTitle = true, // 默认居中 }) : super(key: key); // 根据平台设置不同高度 @override Size get preferredSize { // iOS使用更紧凑的高度(44点),Android保持默认(56点) return Size.fromHeight(Platform.isIOS ? 44.0 : kToolbarHeight); } @override Widget build(BuildContext context) { return AppBar( backgroundColor: backgroundColor, automaticallyImplyLeading: false, centerTitle: centerTitle, toolbarHeight: preferredSize.height, // 使用计算的高度 title: Text( title, style: TextStyle( color: textColor, fontSize: Platform.isIOS ? 17.0 : 18.0, // iOS使用更小字号 fontWeight: FontWeight.w600, // iOS使用中等字重 ), ), leading: isBack ? _buildBackButton(context) : null, actions: _buildActions(), elevation: Platform.isIOS ? 0 : 4, // iOS无阴影 // iOS添加底部边框 shape: Platform.isIOS ? const Border(bottom: BorderSide(color: Colors.black12, width: 0.5)) : null, ); } // 返回按钮 Widget _buildBackButton(BuildContext context) { return Padding( padding: EdgeInsets.only(left: Platform.isIOS ? 8.0 : 16.0), child: IconButton( icon: Icon( Platform.isIOS ? Icons.arrow_back_ios : Icons.arrow_back, color: textColor, size: Platform.isIOS ? 20.0 : 24.0, // iOS使用更小图标 ), padding: EdgeInsets.zero, // 移除默认内边距 constraints: const BoxConstraints(), // 移除默认约束 onPressed: onBackPressed ?? () => Navigator.of(context).pop(), ), ); } // 右侧按钮间距 List? _buildActions() { if (actions == null) return null; return [ Padding( padding: EdgeInsets.only(right: Platform.isIOS ? 8.0 : 16.0), child: Row( mainAxisSize: MainAxisSize.min, children: actions!, ), ) ]; } }