extension_navigation.dart
43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../../get.dart';
import 'dialog/dialog_route.dart';
import 'root/get_root.dart';
/// It replaces the Flutter Navigator, but needs no context.
/// You can to use navigator.push(YourRoute()) rather
/// Navigator.push(context, YourRoute());
NavigatorState? get navigator => GetNavigationExt(Get).key.currentState;
extension ExtensionBottomSheet on GetInterface {
Future<T?> bottomSheet<T>(
Widget bottomsheet, {
Color? backgroundColor,
double? elevation,
bool persistent = true,
ShapeBorder? shape,
Clip? clipBehavior,
Color? barrierColor,
bool? ignoreSafeArea,
bool isScrollControlled = false,
bool useRootNavigator = false,
bool isDismissible = true,
bool enableDrag = true,
RouteSettings? settings,
Duration? enterBottomSheetDuration,
Duration? exitBottomSheetDuration,
Curve? curve,
}) {
return Navigator.of(overlayContext!, rootNavigator: useRootNavigator)
.push(GetModalBottomSheetRoute<T>(
builder: (_) => bottomsheet,
isPersistent: persistent,
// theme: Theme.of(key.currentContext, shadowThemeOnly: true),
theme: Theme.of(key.currentContext!),
isScrollControlled: isScrollControlled,
barrierLabel: MaterialLocalizations.of(key.currentContext!)
.modalBarrierDismissLabel,
backgroundColor: backgroundColor ?? Colors.transparent,
elevation: elevation,
shape: shape,
removeTop: ignoreSafeArea ?? true,
clipBehavior: clipBehavior,
isDismissible: isDismissible,
modalBarrierColor: barrierColor,
settings: settings,
enableDrag: enableDrag,
enterBottomSheetDuration:
enterBottomSheetDuration ?? const Duration(milliseconds: 250),
exitBottomSheetDuration:
exitBottomSheetDuration ?? const Duration(milliseconds: 200),
curve: curve,
));
}
}
extension ExtensionDialog on GetInterface {
/// Show a dialog.
/// You can pass a [transitionDuration] and/or [transitionCurve],
/// overriding the defaults when the dialog shows up and closes.
/// When the dialog closes, uses those animations in reverse.
Future<T?> dialog<T>(
Widget widget, {
bool barrierDismissible = true,
Color? barrierColor,
bool useSafeArea = true,
GlobalKey<NavigatorState>? navigatorKey,
Object? arguments,
Duration? transitionDuration,
Curve? transitionCurve,
String? name,
RouteSettings? routeSettings,
String? id,
}) {
assert(debugCheckHasMaterialLocalizations(context!));
// final theme = Theme.of(context, shadowThemeOnly: true);
final theme = Theme.of(context!);
return generalDialog<T>(
pageBuilder: (buildContext, animation, secondaryAnimation) {
final pageChild = widget;
Widget dialog = Builder(builder: (context) {
return Theme(data: theme, child: pageChild);
});
if (useSafeArea) {
dialog = SafeArea(child: dialog);
}
return dialog;
},
barrierDismissible: barrierDismissible,
barrierLabel: MaterialLocalizations.of(context!).modalBarrierDismissLabel,
barrierColor: barrierColor ?? Colors.black54,
transitionDuration: transitionDuration ?? defaultDialogTransitionDuration,
transitionBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: transitionCurve ?? defaultDialogTransitionCurve,
),
child: child,
);
},
navigatorKey: navigatorKey,
routeSettings:
routeSettings ?? RouteSettings(arguments: arguments, name: name),
id: id,
);
}
/// Api from showGeneralDialog with no context
Future<T?> generalDialog<T>(
{required RoutePageBuilder pageBuilder,
bool barrierDismissible = false,
String? barrierLabel,
Color barrierColor = const Color(0x80000000),
Duration transitionDuration = const Duration(milliseconds: 200),
RouteTransitionsBuilder? transitionBuilder,
GlobalKey<NavigatorState>? navigatorKey,
RouteSettings? routeSettings,
String? id}) {
assert(!barrierDismissible || barrierLabel != null);
final key = navigatorKey ?? Get.nestedKey(id)?.navigatorKey;
final nav = key?.currentState ??
Navigator.of(overlayContext!,
rootNavigator:
true); //overlay context will always return the root navigator
return nav.push<T>(
GetDialogRoute<T>(
pageBuilder: pageBuilder,
barrierDismissible: barrierDismissible,
barrierLabel: barrierLabel,
barrierColor: barrierColor,
transitionDuration: transitionDuration,
transitionBuilder: transitionBuilder,
settings: routeSettings,
),
);
}
/// Custom UI Dialog.
Future<T?> defaultDialog<T>({
String title = "Alert",
EdgeInsetsGeometry? titlePadding,
TextStyle? titleStyle,
Widget? content,
String? id,
EdgeInsetsGeometry? contentPadding,
VoidCallback? onConfirm,
VoidCallback? onCancel,
VoidCallback? onCustom,
Color? cancelTextColor,
Color? confirmTextColor,
String? textConfirm,
String? textCancel,
String? textCustom,
Widget? confirm,
Widget? cancel,
Widget? custom,
Color? backgroundColor,
bool barrierDismissible = true,
Color? buttonColor,
String middleText = "\n",
TextStyle? middleTextStyle,
double radius = 20.0,
// ThemeData themeData,
List<Widget>? actions,
// onWillPop Scope
PopInvokedCallback? onWillPop,
// the navigator used to push the dialog
GlobalKey<NavigatorState>? navigatorKey,
}) {
var leanCancel = onCancel != null || textCancel != null;
var leanConfirm = onConfirm != null || textConfirm != null;
actions ??= [];
if (cancel != null) {
actions.add(cancel);
} else {
if (leanCancel) {
actions.add(TextButton(
style: TextButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
shape: RoundedRectangleBorder(
side: BorderSide(
color: buttonColor ?? theme.colorScheme.secondary,
width: 2,
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(radius)),
),
onPressed: () {
if (onCancel == null) {
//TODO: Close current dialog after api change
closeAllDialogs();
} else {
onCancel.call();
}
},
child: Text(
textCancel ?? "Cancel",
style: TextStyle(
color: cancelTextColor ?? theme.colorScheme.secondary),
),
));
}
}
if (confirm != null) {
actions.add(confirm);
} else {
if (leanConfirm) {
actions.add(TextButton(
style: TextButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
backgroundColor: buttonColor ?? theme.colorScheme.secondary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radius)),
),
child: Text(
textConfirm ?? "Ok",
style: TextStyle(
color: confirmTextColor ?? theme.colorScheme.surface),
),
onPressed: () {
onConfirm?.call();
}));
}
}
Widget baseAlertDialog = AlertDialog(
titlePadding: titlePadding ?? const EdgeInsets.all(8),
contentPadding: contentPadding ?? const EdgeInsets.all(8),
backgroundColor: backgroundColor ?? theme.dialogBackgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(radius))),
title: Text(title, textAlign: TextAlign.center, style: titleStyle),
content: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
content ??
Text(middleText,
textAlign: TextAlign.center, style: middleTextStyle),
const SizedBox(height: 16),
ButtonTheme(
minWidth: 78.0,
height: 34.0,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
runSpacing: 8,
children: actions,
),
)
],
),
// actions: actions, // ?? <Widget>[cancelButton, confirmButton],
buttonPadding: EdgeInsets.zero,
);
return dialog<T>(
onWillPop != null
? PopScope(
onPopInvoked: onWillPop,
child: baseAlertDialog,
)
: baseAlertDialog,
barrierDismissible: barrierDismissible,
navigatorKey: navigatorKey,
id: id,
);
}
}
extension ExtensionSnackbar on GetInterface {
SnackbarController rawSnackbar({
String? title,
String? message,
Widget? titleText,
Widget? messageText,
Widget? icon,
bool instantInit = true,
bool shouldIconPulse = true,
double? maxWidth,
EdgeInsets margin = const EdgeInsets.all(0.0),
EdgeInsets padding = const EdgeInsets.all(16),
double borderRadius = 0.0,
Color? borderColor,
double borderWidth = 1.0,
Color backgroundColor = const Color(0xFF303030),
Color? leftBarIndicatorColor,
List<BoxShadow>? boxShadows,
Gradient? backgroundGradient,
Widget? mainButton,
OnTap? onTap,
Duration? duration = const Duration(seconds: 3),
bool isDismissible = true,
DismissDirection? dismissDirection,
bool showProgressIndicator = false,
AnimationController? progressIndicatorController,
Color? progressIndicatorBackgroundColor,
Animation<Color>? progressIndicatorValueColor,
SnackPosition snackPosition = SnackPosition.bottom,
SnackStyle snackStyle = SnackStyle.floating,
Curve forwardAnimationCurve = Curves.easeOutCirc,
Curve reverseAnimationCurve = Curves.easeOutCirc,
Duration animationDuration = const Duration(seconds: 1),
SnackbarStatusCallback? snackbarStatus,
double barBlur = 0.0,
double overlayBlur = 0.0,
Color? overlayColor,
Form? userInputForm,
}) {
final getSnackBar = GetSnackBar(
snackbarStatus: snackbarStatus,
title: title,
message: message,
titleText: titleText,
messageText: messageText,
snackPosition: snackPosition,
borderRadius: borderRadius,
margin: margin,
duration: duration,
barBlur: barBlur,
backgroundColor: backgroundColor,
icon: icon,
shouldIconPulse: shouldIconPulse,
maxWidth: maxWidth,
padding: padding,
borderColor: borderColor,
borderWidth: borderWidth,
leftBarIndicatorColor: leftBarIndicatorColor,
boxShadows: boxShadows,
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
isDismissible: isDismissible,
dismissDirection: dismissDirection,
showProgressIndicator: showProgressIndicator,
progressIndicatorController: progressIndicatorController,
progressIndicatorBackgroundColor: progressIndicatorBackgroundColor,
progressIndicatorValueColor: progressIndicatorValueColor,
snackStyle: snackStyle,
forwardAnimationCurve: forwardAnimationCurve,
reverseAnimationCurve: reverseAnimationCurve,
animationDuration: animationDuration,
overlayBlur: overlayBlur,
overlayColor: overlayColor,
userInputForm: userInputForm,
);
final controller = SnackbarController(getSnackBar);
if (instantInit) {
controller.show();
} else {
ambiguate(Engine.instance)!.addPostFrameCallback((_) {
controller.show();
});
}
return controller;
}
SnackbarController showSnackbar(GetSnackBar snackbar) {
final controller = SnackbarController(snackbar);
controller.show();
return controller;
}
SnackbarController snackbar(
String title,
String message, {
Color? colorText,
Duration? duration = const Duration(seconds: 3),
/// with instantInit = false you can put snackbar on initState
bool instantInit = true,
SnackPosition? snackPosition,
Widget? titleText,
Widget? messageText,
Widget? icon,
bool? shouldIconPulse,
double? maxWidth,
EdgeInsets? margin,
EdgeInsets? padding,
double? borderRadius,
Color? borderColor,
double? borderWidth,
Color? backgroundColor,
Color? leftBarIndicatorColor,
List<BoxShadow>? boxShadows,
Gradient? backgroundGradient,
TextButton? mainButton,
OnTap? onTap,
OnHover? onHover,
bool? isDismissible,
bool? showProgressIndicator,
DismissDirection? dismissDirection,
AnimationController? progressIndicatorController,
Color? progressIndicatorBackgroundColor,
Animation<Color>? progressIndicatorValueColor,
SnackStyle? snackStyle,
Curve? forwardAnimationCurve,
Curve? reverseAnimationCurve,
Duration? animationDuration,
double? barBlur,
double? overlayBlur,
SnackbarStatusCallback? snackbarStatus,
Color? overlayColor,
Form? userInputForm,
}) {
final getSnackBar = GetSnackBar(
snackbarStatus: snackbarStatus,
titleText: titleText ??
Text(
title,
style: TextStyle(
color: colorText ?? iconColor ?? Colors.black,
fontWeight: FontWeight.w800,
fontSize: 16,
),
),
messageText: messageText ??
Text(
message,
style: TextStyle(
color: colorText ?? iconColor ?? Colors.black,
fontWeight: FontWeight.w300,
fontSize: 14,
),
),
snackPosition: snackPosition ?? SnackPosition.top,
borderRadius: borderRadius ?? 15,
margin: margin ?? const EdgeInsets.symmetric(horizontal: 10),
duration: duration,
barBlur: barBlur ?? 7.0,
backgroundColor: backgroundColor ?? Colors.grey.withOpacity(0.2),
icon: icon,
shouldIconPulse: shouldIconPulse ?? true,
maxWidth: maxWidth,
padding: padding ?? const EdgeInsets.all(16),
borderColor: borderColor,
borderWidth: borderWidth,
leftBarIndicatorColor: leftBarIndicatorColor,
boxShadows: boxShadows,
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
onHover: onHover,
isDismissible: isDismissible ?? true,
dismissDirection: dismissDirection,
showProgressIndicator: showProgressIndicator ?? false,
progressIndicatorController: progressIndicatorController,
progressIndicatorBackgroundColor: progressIndicatorBackgroundColor,
progressIndicatorValueColor: progressIndicatorValueColor,
snackStyle: snackStyle ?? SnackStyle.floating,
forwardAnimationCurve: forwardAnimationCurve ?? Curves.easeOutCirc,
reverseAnimationCurve: reverseAnimationCurve ?? Curves.easeOutCirc,
animationDuration: animationDuration ?? const Duration(seconds: 1),
overlayBlur: overlayBlur ?? 0.0,
overlayColor: overlayColor ?? Colors.transparent,
userInputForm: userInputForm);
final controller = SnackbarController(getSnackBar);
if (instantInit) {
controller.show();
} else {
//routing.isSnackbar = true;
ambiguate(Engine.instance)!.addPostFrameCallback((_) {
controller.show();
});
}
return controller;
}
}
extension GetNavigationExt on GetInterface {
/// **Navigation.push()** shortcut.<br><br>
///
/// Pushes a new `page` to the stack
///
/// It has the advantage of not needing context,
/// so you can call from your business logic
///
/// You can set a custom [transition], and a transition [duration].
///
/// You can send any type of value to the other route in the [arguments].
///
/// Just like native routing in Flutter, you can push a route
/// as a [fullscreenDialog],
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// If you want the same behavior of ios that pops a route when the user drag,
/// you can set [popGesture] to true
///
/// If you're using the [BindingsInterface] api, you must define it here
///
/// By default, GetX will prevent you from push a route that you already in,
/// if you want to push anyway, set [preventDuplicates] to false
Future<T?>? to<T extends Object?>(Widget Function() page,
{bool? opaque,
Transition? transition,
Curve? curve,
Duration? duration,
String? id,
String? routeName,
bool fullscreenDialog = false,
dynamic arguments,
List<BindingsInterface> bindings = const [],
bool preventDuplicates = true,
bool? popGesture,
bool showCupertinoParallax = true,
double Function(BuildContext context)? gestureWidth,
bool rebuildStack = true,
PreventDuplicateHandlingMode preventDuplicateHandlingMode =
PreventDuplicateHandlingMode.reorderRoutes}) {
return searchDelegate(id).to(
page,
opaque: opaque,
transition: transition,
curve: curve,
duration: duration,
id: id,
routeName: routeName,
fullscreenDialog: fullscreenDialog,
arguments: arguments,
bindings: bindings,
preventDuplicates: preventDuplicates,
popGesture: popGesture,
showCupertinoParallax: showCupertinoParallax,
gestureWidth: gestureWidth,
rebuildStack: rebuildStack,
preventDuplicateHandlingMode: preventDuplicateHandlingMode,
);
}
// GetPageBuilder _resolvePage(dynamic page, String method) {
// if (page is GetPageBuilder) {
// return page;
// } else if (page is Widget) {
// Get.log(
// '''WARNING, consider using: "Get.$method(() => Page())"
//instead of "Get.$method(Page())".
// Using a widget function instead of a widget fully guarantees that the widget
//and its controllers will be removed from memory when they are no longer used.
// ''');
// return () => page;
// } else if (page is String) {
// throw '''Unexpected String,
// use toNamed() instead''';
// } else {
// throw '''Unexpected format,
// you can only use widgets and widget functions here''';
// }
// }
/// **Navigation.pushNamed()** shortcut.<br><br>
///
/// Pushes a new named `page` to the stack.
///
/// It has the advantage of not needing context, so you can call
/// from your business logic.
///
/// You can send any type of value to the other route in the [arguments].
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// By default, GetX will prevent you from push a route that you already in,
/// if you want to push anyway, set [preventDuplicates] to false
///
/// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors
Future<T?>? toNamed<T>(
String page, {
dynamic arguments,
dynamic id,
bool preventDuplicates = true,
Map<String, String>? parameters,
}) {
// if (preventDuplicates && page == currentRoute) {
// return null;
// }
if (parameters != null) {
final uri = Uri(path: page, queryParameters: parameters);
page = uri.toString();
}
return searchDelegate(id).toNamed(
page,
arguments: arguments,
id: id,
preventDuplicates: preventDuplicates,
parameters: parameters,
);
}
/// **Navigation.pushReplacementNamed()** shortcut.<br><br>
///
/// Pop the current named `page` in the stack and push a new one in its place
///
/// It has the advantage of not needing context, so you can call
/// from your business logic.
///
/// You can send any type of value to the other route in the [arguments].
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// By default, GetX will prevent you from push a route that you already in,
/// if you want to push anyway, set [preventDuplicates] to false
///
/// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors
Future<T?>? offNamed<T>(
String page, {
dynamic arguments,
String? id,
Map<String, String>? parameters,
}) {
// if (preventDuplicates && page == currentRoute) {
// return null;
// }
if (parameters != null) {
final uri = Uri(path: page, queryParameters: parameters);
page = uri.toString();
}
return searchDelegate(id).offNamed(
page,
arguments: arguments,
id: id,
// preventDuplicates: preventDuplicates,
parameters: parameters,
);
}
/// **Navigation.popUntil()** shortcut.<br><br>
///
/// Calls pop several times in the stack until [predicate] returns true
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// [predicate] can be used like this:
/// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page,
///
/// or also like this:
/// `Get.until((route) => !Get.isDialogOpen())`, to make sure the
/// dialog is closed
void until(bool Function(GetPage<dynamic>) predicate, {String? id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return searchDelegate(id).backUntil(predicate);
}
/// **Navigation.pushNamedAndRemoveUntil()** shortcut.<br><br>
///
/// Push the given named `page`, and then pop several pages in the stack
/// until [predicate] returns true
///
/// You can send any type of value to the other route in the [arguments].
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// [predicate] can be used like this:
/// `Get.offNamedUntil(page, ModalRoute.withName('/home'))`
/// to pop routes in stack until home,
/// or like this:
/// `Get.offNamedUntil((route) => !Get.isDialogOpen())`,
/// to make sure the dialog is closed
///
/// Note: Always put a slash on the route name ('/page1'), to avoid unexpected errors
Future<T?>? offNamedUntil<T>(
String page,
bool Function(GetPage<dynamic>)? predicate, {
String? id,
dynamic arguments,
Map<String, String>? parameters,
}) {
if (parameters != null) {
final uri = Uri(path: page, queryParameters: parameters);
page = uri.toString();
}
return searchDelegate(id).offNamedUntil<T>(
page,
predicate: predicate,
id: id,
arguments: arguments,
parameters: parameters,
);
}
/// **Navigation.popAndPushNamed()** shortcut.<br><br>
///
/// Pop the current named page and pushes a new `page` to the stack
/// in its place
///
/// You can send any type of value to the other route in the [arguments].
/// It is very similar to `offNamed()` but use a different approach
///
/// The `offNamed()` pop a page, and goes to the next. The
/// `offAndToNamed()` goes to the next page, and removes the previous one.
/// The route transition animation is different.
Future<T?>? offAndToNamed<T>(
String page, {
dynamic arguments,
String? id,
dynamic result,
Map<String, String>? parameters,
}) {
if (parameters != null) {
final uri = Uri(path: page, queryParameters: parameters);
page = uri.toString();
}
return searchDelegate(id).backAndtoNamed(
page,
arguments: arguments,
result: result,
);
}
/// **Navigation.removeRoute()** shortcut.<br><br>
///
/// Remove a specific [route] from the stack
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
void removeRoute(String name, {String? id}) {
return searchDelegate(id).removeRoute(name);
}
/// **Navigation.pushNamedAndRemoveUntil()** shortcut.<br><br>
///
/// Push a named `page` and pop several pages in the stack
/// until [predicate] returns true. [predicate] is optional
///
/// It has the advantage of not needing context, so you can
/// call from your business logic.
///
/// You can send any type of value to the other route in the [arguments].
///
/// [predicate] can be used like this:
/// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page,
/// or also like
/// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog
/// is closed
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors
Future<T?>? offAllNamed<T>(
String newRouteName, {
// bool Function(GetPage<dynamic>)? predicate,
dynamic arguments,
String? id,
Map<String, String>? parameters,
}) {
if (parameters != null) {
final uri = Uri(path: newRouteName, queryParameters: parameters);
newRouteName = uri.toString();
}
return searchDelegate(id).offAllNamed<T>(
newRouteName,
//predicate: predicate ?? (_) => false,
arguments: arguments,
id: id,
parameters: parameters,
);
}
/// Returns true if a Snackbar, Dialog or BottomSheet is currently OPEN
bool get isOverlaysOpen =>
(isSnackbarOpen || isDialogOpen! || isBottomSheetOpen!);
/// Returns true if there is no Snackbar, Dialog or BottomSheet open
bool get isOverlaysClosed =>
(!isSnackbarOpen && !isDialogOpen! && !isBottomSheetOpen!);
/// **Navigation.popUntil()** shortcut.<br><br>
///
/// Pop the current page, snackbar, dialog or bottomsheet in the stack
///
/// if your set [closeOverlays] to true, Get.back() will close the
/// currently open snackbar/dialog/bottomsheet AND the current page
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// It has the advantage of not needing context, so you can call
/// from your business logic.
void back<T>({
T? result,
bool canPop = true,
int times = 1,
String? id,
}) {
if (times < 1) {
times = 1;
}
if (times > 1) {
var count = 0;
return searchDelegate(id).backUntil((route) => count++ == times);
} else {
if (canPop) {
if (searchDelegate(id).canBack == true) {
return searchDelegate(id).back<T>(result);
}
} else {
return searchDelegate(id).back<T>(result);
}
}
}
/// Pop the current page, snackbar, dialog or bottomsheet in the stack
///
/// if your set [closeOverlays] to true, Get.back() will close the
/// currently open snackbar/dialog/bottomsheet AND the current page
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// It has the advantage of not needing context, so you can call
/// from your business logic.
void backLegacy<T>({
T? result,
bool closeOverlays = false,
bool canPop = true,
int times = 1,
String? id,
}) {
if (closeOverlays) {
closeAllOverlays();
}
if (times < 1) {
times = 1;
}
if (times > 1) {
var count = 0;
return searchDelegate(id).navigatorKey.currentState?.popUntil((route) {
return count++ == times;
});
} else {
if (canPop) {
if (searchDelegate(id).navigatorKey.currentState?.canPop() == true) {
return searchDelegate(id).navigatorKey.currentState?.pop<T>(result);
}
} else {
return searchDelegate(id).navigatorKey.currentState?.pop<T>(result);
}
}
}
void closeAllDialogsAndBottomSheets(
String? id,
) {
// It can not be divided, because dialogs and bottomsheets can not be consecutive
while ((isDialogOpen! && isBottomSheetOpen!)) {
closeOverlay(id: id);
}
}
void closeAllDialogs({
String? id,
}) {
while ((isDialogOpen!)) {
closeOverlay(id: id);
}
}
void closeOverlay({String? id}) {
searchDelegate(id).navigatorKey.currentState?.pop();
}
void closeAllBottomSheets({
String? id,
}) {
while ((isBottomSheetOpen!)) {
searchDelegate(id).navigatorKey.currentState?.pop();
}
}
void closeAllOverlays() {
closeAllDialogsAndBottomSheets(null);
closeAllSnackbars();
}
/// **Navigation.popUntil()** (with predicate) shortcut .<br><br>
///
/// Close as many routes as defined by [times]
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
void close<T extends Object>({
bool closeAll = true,
bool closeSnackbar = true,
bool closeDialog = true,
bool closeBottomSheet = true,
String? id,
T? result,
}) {
void handleClose(bool closeCondition, Function closeAllFunction,
Function closeSingleFunction,
[bool? isOpenCondition]) {
if (closeCondition) {
if (closeAll) {
closeAllFunction();
} else if (isOpenCondition == true) {
closeSingleFunction();
}
}
}
handleClose(closeSnackbar, closeAllSnackbars, closeCurrentSnackbar);
handleClose(closeDialog, closeAllDialogs, closeOverlay, isDialogOpen);
handleClose(closeBottomSheet, closeAllBottomSheets, closeOverlay,
isBottomSheetOpen);
}
/// **Navigation.pushReplacement()** shortcut .<br><br>
///
/// Pop the current page and pushes a new `page` to the stack
///
/// It has the advantage of not needing context,
/// so you can call from your business logic
///
/// You can set a custom [transition], define a Tween [curve],
/// and a transition [duration].
///
/// You can send any type of value to the other route in the [arguments].
///
/// Just like native routing in Flutter, you can push a route
/// as a [fullscreenDialog],
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// If you want the same behavior of ios that pops a route when the user drag,
/// you can set [popGesture] to true
///
/// If you're using the [BindingsInterface] api, you must define it here
///
/// By default, GetX will prevent you from push a route that you already in,
/// if you want to push anyway, set [preventDuplicates] to false
Future<T?>? off<T>(
Widget Function() page, {
bool? opaque,
Transition? transition,
Curve? curve,
bool? popGesture,
String? id,
String? routeName,
dynamic arguments,
List<BindingsInterface> bindings = const [],
bool fullscreenDialog = false,
bool preventDuplicates = true,
Duration? duration,
double Function(BuildContext context)? gestureWidth,
}) {
routeName ??= "/${page.runtimeType.toString()}";
routeName = _cleanRouteName(routeName);
if (preventDuplicates && routeName == currentRoute) {
return null;
}
return searchDelegate(id).off(
page,
opaque: opaque ?? true,
transition: transition,
curve: curve,
popGesture: popGesture,
id: id,
routeName: routeName,
arguments: arguments,
bindings: bindings,
fullscreenDialog: fullscreenDialog,
preventDuplicates: preventDuplicates,
duration: duration,
gestureWidth: gestureWidth,
);
}
Future<T?> offUntil<T>(
Widget Function() page,
bool Function(GetPage) predicate, [
Object? arguments,
String? id,
]) {
return searchDelegate(id).offUntil(
page,
predicate,
arguments,
);
}
///
/// Push a `page` and pop several pages in the stack
/// until [predicate] returns true. [predicate] is optional
///
/// It has the advantage of not needing context,
/// so you can call from your business logic
///
/// You can set a custom [transition], a [curve] and a transition [duration].
///
/// You can send any type of value to the other route in the [arguments].
///
/// Just like native routing in Flutter, you can push a route
/// as a [fullscreenDialog],
///
/// [predicate] can be used like this:
/// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page,
/// or also like
/// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog
/// is closed
///
/// [id] is for when you are using nested navigation,
/// as explained in documentation
///
/// If you want the same behavior of ios that pops a route when the user drag,
/// you can set [popGesture] to true
///
/// If you're using the [BindingsInterface] api, you must define it here
///
/// By default, GetX will prevent you from push a route that you already in,
/// if you want to push anyway, set [preventDuplicates] to false
Future<T?>? offAll<T>(
Widget Function() page, {
bool Function(GetPage<dynamic>)? predicate,
bool? opaque,
bool? popGesture,
String? id,
String? routeName,
dynamic arguments,
List<BindingsInterface> bindings = const [],
bool fullscreenDialog = false,
Transition? transition,
Curve? curve,
Duration? duration,
double Function(BuildContext context)? gestureWidth,
}) {
routeName ??= "/${page.runtimeType.toString()}";
routeName = _cleanRouteName(routeName);
return searchDelegate(id).offAll<T>(
page,
predicate: predicate,
opaque: opaque ?? true,
popGesture: popGesture,
id: id,
// routeName routeName,
arguments: arguments,
bindings: bindings,
fullscreenDialog: fullscreenDialog,
transition: transition,
curve: curve,
duration: duration,
gestureWidth: gestureWidth,
);
}
/// Takes a route [name] String generated by [to], [off], [offAll]
/// (and similar context navigation methods), cleans the extra chars and
/// accommodates the format.
/// TODO: check for a more "appealing" URL naming convention.
/// `() => MyHomeScreenView` becomes `/my-home-screen-view`.
String _cleanRouteName(String name) {
name = name.replaceAll('() => ', '');
/// uncomment for URL styling.
// name = name.paramCase!;
if (!name.startsWith('/')) {
name = '/$name';
}
return Uri.tryParse(name)?.toString() ?? name;
}
//TODO: Deprecated
// /// change default config of Get
// void config(
// {bool? enableLog,
// LogWriterCallback? logWriterCallback,
// bool? defaultPopGesture,
// bool? defaultOpaqueRoute,
// Duration? defaultDurationTransition,
// bool? defaultGlobalState,
// Transition? defaultTransition}) {
// if (enableLog != null) {
// Get.isLogEnable = enableLog;
// }
// if (logWriterCallback != null) {
// Get.log = logWriterCallback;
// }
// if (defaultPopGesture != null) {
// _getxController.defaultPopGesture = defaultPopGesture;
// }
// if (defaultOpaqueRoute != null) {
// _getxController.defaultOpaqueRoute = defaultOpaqueRoute;
// }
// if (defaultTransition != null) {
// _getxController.defaultTransition = defaultTransition;
// }
// if (defaultDurationTransition != null) {
// _getxController.defaultTransitionDuration = defaultDurationTransition;
// }
// }
Future<void> updateLocale(Locale l) async {
Get.locale = l;
await forceAppUpdate();
}
/// As a rule, Flutter knows which widget to update,
/// so this command is rarely needed. We can mention situations
/// where you use const so that widgets are not updated with setState,
/// but you want it to be forcefully updated when an event like
/// language change happens. using context to make the widget dirty
/// for performRebuild() is a viable solution.
/// However, in situations where this is not possible, or at least,
/// is not desired by the developer, the only solution for updating
/// widgets that Flutter does not want to update is to use reassemble
/// to forcibly rebuild all widgets. Attention: calling this function will
/// reconstruct the application from the sketch, use this with caution.
/// Your entire application will be rebuilt, and touch events will not
/// work until the end of rendering.
Future<void> forceAppUpdate() async {
await engine.performReassemble();
}
void appUpdate() => rootController.update();
void changeTheme(ThemeData theme) {
rootController.setTheme(theme);
}
void changeThemeMode(ThemeMode themeMode) {
rootController.setThemeMode(themeMode);
}
GlobalKey<NavigatorState>? addKey(GlobalKey<NavigatorState> newKey) {
return rootController.addKey(newKey);
}
GetDelegate? nestedKey(String? key) {
return rootController.nestedKey(key);
}
GetDelegate searchDelegate(String? k) {
GetDelegate key;
if (k == null) {
key = Get.rootController.rootDelegate;
} else {
if (!keys.containsKey(k)) {
throw 'Route id ($k) not found';
}
key = keys[k]!;
}
// if (_key.listenersLength == 0 && !testMode) {
// throw """You are trying to use contextless navigation without
// a GetMaterialApp or Get.key.
// If you are testing your app, you can use:
// [Get.testMode = true], or if you are running your app on
// a physical device or emulator, you must exchange your [MaterialApp]
// for a [GetMaterialApp].
// """;
// }
return key;
}
/// give current arguments
//dynamic get arguments => routing.args;
dynamic get arguments => rootController.rootDelegate.arguments();
/// give name from current route
String get currentRoute => routing.current;
/// give name from previous route
String get previousRoute => routing.previous;
/// check if snackbar is open
bool get isSnackbarOpen =>
SnackbarController.isSnackbarBeingShown; //routing.isSnackbar;
void closeAllSnackbars() {
SnackbarController.cancelAllSnackbars();
}
Future<void> closeCurrentSnackbar() async {
await SnackbarController.closeCurrentSnackbar();
}
/// check if dialog is open
bool? get isDialogOpen => routing.isDialog;
/// check if bottomsheet is open
bool? get isBottomSheetOpen => routing.isBottomSheet;
/// check a raw current route
Route<dynamic>? get rawRoute => routing.route;
/// check if popGesture is enable
bool get isPopGestureEnable => defaultPopGesture;
/// check if default opaque route is enable
bool get isOpaqueRouteDefault => defaultOpaqueRoute;
/// give access to currentContext
BuildContext? get context => key.currentContext;
/// give access to current Overlay Context
BuildContext? get overlayContext {
BuildContext? overlay;
key.currentState?.overlay?.context.visitChildElements((element) {
overlay = element;
});
return overlay;
}
/// give access to Theme.of(context)
ThemeData get theme {
var theme = ThemeData.fallback();
if (context != null) {
theme = Theme.of(context!);
}
return theme;
}
/// The current null safe [WidgetsBinding]
WidgetsBinding get engine {
return WidgetsFlutterBinding.ensureInitialized();
}
/// The window to which this binding is bound.
ui.PlatformDispatcher get window => engine.platformDispatcher;
Locale? get deviceLocale => window.locale;
///The number of device pixels for each logical pixel.
double get pixelRatio => window.implicitView!.devicePixelRatio;
Size get size => window.implicitView!.physicalSize / pixelRatio;
///The horizontal extent of this size.
double get width => size.width;
///The vertical extent of this size
double get height => size.height;
///The distance from the top edge to the first unpadded pixel,
///in physical pixels.
double get statusBarHeight => window.implicitView!.padding.top;
///The distance from the bottom edge to the first unpadded pixel,
///in physical pixels.
double get bottomBarHeight => window.implicitView!.padding.bottom;
///The system-reported text scale.
double get textScaleFactor => window.textScaleFactor;
/// give access to TextTheme.of(context)
TextTheme get textTheme => theme.textTheme;
/// give access to Mediaquery.of(context)
MediaQueryData get mediaQuery => MediaQuery.of(context!);
/// Check if dark mode theme is enable
bool get isDarkMode => (theme.brightness == Brightness.dark);
/// Check if dark mode theme is enable on platform on android Q+
bool get isPlatformDarkMode =>
(ui.PlatformDispatcher.instance.platformBrightness == Brightness.dark);
/// give access to Theme.of(context).iconTheme.color
Color? get iconColor => theme.iconTheme.color;
/// give access to FocusScope.of(context)
FocusNode? get focusScope => FocusManager.instance.primaryFocus;
// /// give access to Immutable MediaQuery.of(context).size.height
// double get height => MediaQuery.of(context).size.height;
// /// give access to Immutable MediaQuery.of(context).size.width
// double get width => MediaQuery.of(context).size.width;
GlobalKey<NavigatorState> get key => rootController.key;
Map<String, GetDelegate> get keys => rootController.keys;
GetRootState get rootController => GetRootState.controller;
ConfigData get _getxController => GetRootState.controller.config;
bool get defaultPopGesture => _getxController.defaultPopGesture;
bool get defaultOpaqueRoute => _getxController.defaultOpaqueRoute;
Transition? get defaultTransition => _getxController.defaultTransition;
Duration get defaultTransitionDuration {
return _getxController.defaultTransitionDuration;
}
Curve get defaultTransitionCurve => _getxController.defaultTransitionCurve;
Curve get defaultDialogTransitionCurve {
return _getxController.defaultDialogTransitionCurve;
}
Duration get defaultDialogTransitionDuration {
return _getxController.defaultDialogTransitionDuration;
}
Routing get routing => _getxController.routing;
set parameters(Map<String, String?> newParameters) =>
rootController.parameters = newParameters;
set testMode(bool isTest) => rootController.testMode = isTest;
bool get testMode => _getxController.testMode;
Map<String, String?> get parameters => rootController.rootDelegate.parameters;
/// Casts the stored router delegate to a desired type
TDelegate? delegate<TDelegate extends RouterDelegate<TPage>, TPage>() =>
_getxController.routerDelegate as TDelegate?;
}
extension OverlayExt on GetInterface {
Future<T> showOverlay<T>({
required Future<T> Function() asyncFunction,
Color opacityColor = Colors.black,
Widget? loadingWidget,
double opacity = .5,
}) async {
final navigatorState =
Navigator.of(Get.overlayContext!, rootNavigator: false);
final overlayState = navigatorState.overlay!;
final overlayEntryOpacity = OverlayEntry(builder: (context) {
return Opacity(
opacity: opacity,
child: Container(
color: opacityColor,
));
});
final overlayEntryLoader = OverlayEntry(builder: (context) {
return loadingWidget ??
const Center(
child: SizedBox(
height: 90,
width: 90,
child: Text('Loading...'),
));
});
overlayState.insert(overlayEntryOpacity);
overlayState.insert(overlayEntryLoader);
T data;
try {
data = await asyncFunction();
} on Exception catch (_) {
overlayEntryLoader.remove();
overlayEntryOpacity.remove();
rethrow;
}
overlayEntryLoader.remove();
overlayEntryOpacity.remove();
return data;
}
}