82 lines
2.3 KiB
Dart
82 lines
2.3 KiB
Dart
import 'package:flutter/material.dart';
|
||
|
||
import '../utils/haptics.dart';
|
||
import '../utils/url_opener.dart';
|
||
import 'async_action_button.dart';
|
||
|
||
class ConfirmDialog extends StatelessWidget {
|
||
final String title;
|
||
final String content;
|
||
final IconData? icon;
|
||
final String confirmButton;
|
||
|
||
/// Label of the cancel button. Set to `null` for a single-button dialog
|
||
/// (only the confirm action is rendered).
|
||
final String? cancelButton;
|
||
|
||
/// Optional: without [onConfirm]/[onConfirmAsync] the dialog only reports
|
||
/// the decision via [ask].
|
||
final void Function()? onConfirm;
|
||
final AsyncActionCallback? onConfirmAsync;
|
||
final AsyncErrorBuilder? errorBuilder;
|
||
|
||
const ConfirmDialog({
|
||
super.key,
|
||
required this.title,
|
||
this.content = '',
|
||
this.icon,
|
||
this.confirmButton = 'Ok',
|
||
this.cancelButton = 'Abbrechen',
|
||
this.onConfirm,
|
||
this.onConfirmAsync,
|
||
this.errorBuilder,
|
||
});
|
||
|
||
void asDialog(BuildContext context) {
|
||
showDialog(context: context, builder: build);
|
||
}
|
||
|
||
/// Resolves to true once confirmed – with [onConfirmAsync] only after it
|
||
/// succeeded.
|
||
Future<bool> ask(BuildContext context) async =>
|
||
await showDialog<bool>(context: context, builder: build) ?? false;
|
||
|
||
@override
|
||
Widget build(BuildContext context) => AlertDialog(
|
||
icon: icon != null ? Icon(icon) : null,
|
||
title: Text(title),
|
||
content: Text(content),
|
||
actions: onConfirmAsync != null
|
||
? [
|
||
AsyncDialogAction(
|
||
confirmLabel: confirmButton,
|
||
cancelLabel: cancelButton,
|
||
onConfirm: onConfirmAsync!,
|
||
errorBuilder: errorBuilder,
|
||
),
|
||
]
|
||
: [
|
||
if (cancelButton != null)
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: Text(cancelButton!),
|
||
),
|
||
TextButton(
|
||
onPressed: () {
|
||
Haptics.confirm();
|
||
Navigator.of(context).pop(true);
|
||
onConfirm?.call();
|
||
},
|
||
child: Text(confirmButton),
|
||
),
|
||
],
|
||
);
|
||
|
||
static void openBrowser(BuildContext context, String url) => ConfirmDialog(
|
||
title: 'Link öffnen',
|
||
content: 'Möchtest du den folgenden Link öffnen?\n$url',
|
||
confirmButton: 'Öffnen',
|
||
onConfirm: () => UrlOpener.openUrl(url),
|
||
).asDialog(context);
|
||
}
|