import 'package:flutter/material.dart'; import 'package:get/get.dart'; class VAlertDialog extends StatelessWidget { /// 标题 final String? title; /// 内容 final Widget content; /// 内容内距 final EdgeInsetsGeometry? contentPadding; /// 宽度 final double width; /// 确定按钮文本 final String confirmLabel; /// 取消按钮文本 final String cancelLabel; /// 取消回调 final VoidCallback? onCanceled; /// 确定回调,不为空则显示确定按钮 final VoidCallback? onConfirm; /// 是否显示取消按钮 final bool showCancel; const VAlertDialog({ super.key, this.title, required this.content, this.contentPadding, this.width = 460, this.confirmLabel = "确定", this.cancelLabel = "取消", this.onCanceled, this.onConfirm, this.showCancel = true, }); static Future showDialog( Widget child, [ bool barrierDismissible = false, ]) async { return await Get.dialog( child, barrierDismissible: barrierDismissible, barrierColor: Colors.black.withOpacity(.4), ); } @override Widget build(BuildContext context) { final actions = _buildActions(context); final hasActions = actions != null && actions.length > 1; return AlertDialog( backgroundColor: Colors.white, elevation: 0, title: title != null ? Text(title!) : null, titleTextStyle: const TextStyle(fontSize: 24, color: Colors.black), actionsAlignment: hasActions ? MainAxisAlignment.spaceAround : MainAxisAlignment.center, actions: actions, contentPadding: contentPadding ?? const EdgeInsets.only(top: 20, bottom: 8), content: SizedBox( width: width, child: content, ), ); } List? _buildActions(BuildContext context) { final widgets = []; final showConfirm = onConfirm != null; double btnWidth = 0; if (showCancel && showConfirm) { btnWidth = (width - 20) / 2; } else { if (showCancel || showConfirm) { btnWidth = width - 12; } } if (showCancel) { widgets.add( _AlertActionButton( width: btnWidth, label: cancelLabel, onPressed: () { Navigator.of(context).pop(); onCanceled?.call(); }, ), ); } if (showConfirm) { if (widgets.isNotEmpty) { widgets.add( SizedBox( height: 24, child: VerticalDivider( thickness: 1, color: Colors.black.withOpacity(.4), ), ), ); } widgets.add( _AlertActionButton( width: btnWidth, label: confirmLabel, onPressed: () { onConfirm!.call(); }, ), ); } return widgets; } } class _AlertActionButton extends StatelessWidget { final String label; final double width; final VoidCallback onPressed; const _AlertActionButton({ super.key, required this.label, required this.onPressed, required this.width, }); @override Widget build(BuildContext context) { return SizedBox( width: width, height: 48, child: TextButton( onPressed: onPressed, child: Text( label, style: const TextStyle(fontSize: 18), ), ), ); } }