Skip to content

Commit cb5d94d

Browse files
committed
✨ Improved native dialog function. To also include a result when needed.
1 parent da05b53 commit cb5d94d

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

lib/ui/native_dialog.dart

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:async';
2+
13
import 'package:flutter/cupertino.dart';
24
import 'package:flutter/foundation.dart';
35
import 'package:flutter/material.dart';
@@ -15,14 +17,14 @@ import 'package:flutter/material.dart';
1517
/// ],
1618
/// );
1719
/// ```
18-
void showNativeDialog(
20+
Future<T?> showNativeDialog<T>(
1921
BuildContext context, {
2022
required String title,
21-
required List<DialogAction> actions,
23+
required List<DialogAction<T>> actions,
2224
required String content,
2325
}) {
2426
if (defaultTargetPlatform == TargetPlatform.iOS) {
25-
showCupertinoDialog<void>(
27+
return showCupertinoDialog<T>(
2628
context: context,
2729
builder:
2830
(dialogContext) => CupertinoAlertDialog(
@@ -32,9 +34,9 @@ void showNativeDialog(
3234
actions
3335
.map(
3436
(action) => CupertinoDialogAction(
35-
onPressed: () {
36-
action.onTap();
37-
Navigator.of(dialogContext).pop();
37+
onPressed: () async {
38+
final result = await action.onTap();
39+
if (dialogContext.mounted) Navigator.of(dialogContext).pop(result);
3840
},
3941
isDestructiveAction: action.isDestructiveAction,
4042
child: Text(action.text),
@@ -44,7 +46,7 @@ void showNativeDialog(
4446
),
4547
);
4648
} else {
47-
showDialog<void>(
49+
return showDialog<T?>(
4850
context: context,
4951
builder:
5052
(dialogContext) => AlertDialog(
@@ -54,9 +56,9 @@ void showNativeDialog(
5456
actions
5557
.map(
5658
(action) => TextButton(
57-
onPressed: () {
58-
action.onTap();
59-
Navigator.of(dialogContext).pop();
59+
onPressed: () async {
60+
final result = await action.onTap();
61+
if (dialogContext.mounted) Navigator.of(dialogContext).pop(result);
6062
},
6163
child: Text(action.text),
6264
),
@@ -68,15 +70,15 @@ void showNativeDialog(
6870
}
6971

7072
/// A dialog action which is used to show the actions of a native dialog. Tapping a action will also close the dialog.
71-
class DialogAction {
73+
class DialogAction<T> {
7274
/// Creates a [DialogAction].
7375
const DialogAction({required this.text, required this.onTap, this.isDestructiveAction = false});
7476

7577
/// The text of the action.
7678
final String text;
7779

7880
/// The callback that is called when the action is tapped.
79-
final VoidCallback onTap;
81+
final FutureOr<T?> Function() onTap;
8082

8183
/// Whether the action is a destructive action. This is only used on iOS.
8284
final bool isDestructiveAction;

0 commit comments

Comments
 (0)