get_router_delegate.dart
9.23 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
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get_navigation/src/nav2/router_outlet.dart';
import '../../../get.dart';
import '../../../get_state_manager/src/simple/list_notifier.dart';
/// Enables the user to customize the intended pop behavior
///
/// Goes to either the previous history entry or the previous page entry
///
/// e.g. if the user navigates to these pages
/// 1) /home
/// 2) /home/products/1234
///
/// when popping on [History] mode, it will emulate a browser back button.
///
/// so the new history stack will be:
/// 1) /home
///
/// when popping on [Page] mode, it will only remove the last part of the route
/// so the new history stack will be:
/// 1) /home
/// 2) /home/products
///
/// another pop will change the history stack to:
/// 1) /home
enum PopMode {
History,
Page,
}
/// Enables the user to customize the behavior when pushing multiple routes that
/// shouldn't be duplicates
enum PreventDuplicateHandlingMode {
/// Removes the history entries until it reaches the old route
PopUntilOriginalRoute,
/// Simply don't push the new route
DoNothing,
}
class GetDelegate extends RouterDelegate<GetNavConfig>
with ListenableMixin, ListNotifierMixin {
final List<GetNavConfig> history = <GetNavConfig>[];
final PopMode backButtonPopMode;
final PreventDuplicateHandlingMode preventDuplicateHandlingMode;
GetPage? notFoundRoute;
final List<NavigatorObserver>? navigatorObservers;
final TransitionDelegate<dynamic>? transitionDelegate;
final _resultCompleter = <GetNavConfig, Completer<Object?>>{};
GlobalKey<NavigatorState> get navigatorKey =>
GetNavigation.getxController.key;
GetDelegate({
this.notFoundRoute,
this.navigatorObservers,
this.transitionDelegate,
this.backButtonPopMode = PopMode.History,
this.preventDuplicateHandlingMode = PreventDuplicateHandlingMode.DoNothing,
});
/// Adds a new history entry and waits for the result
Future<T?> pushHistory<T>(
GetNavConfig config, {
bool rebuildStack = true,
}) {
//this changes the currentConfiguration
final completer = Completer<T?>();
_resultCompleter[config] = completer;
_pushHistory(config);
if (rebuildStack) {
refresh();
}
return completer.future;
}
void _removeHistoryEntry(GetNavConfig entry) {
history.remove(entry);
final lastCompleter = _resultCompleter.remove(entry);
lastCompleter?.complete(entry);
}
void _pushHistory(GetNavConfig config) {
if (config.currentPage!.preventDuplicates) {
if (history.any((element) => element.location == config.location)) {
switch (preventDuplicateHandlingMode) {
case PreventDuplicateHandlingMode.PopUntilOriginalRoute:
until(config.location!, popMode: PopMode.Page);
return;
case PreventDuplicateHandlingMode.DoNothing:
default:
return;
}
}
}
history.add(config);
}
GetPageRoute getPageRoute(RouteSettings? settings) {
return PageRedirect(settings ?? RouteSettings(name: '/404'), _notFound())
.page();
}
GetNavConfig? _popHistory() {
if (!_canPopHistory()) return null;
return _doPopHistory();
}
GetNavConfig _doPopHistory() {
final res = history.removeLast();
return res;
}
GetNavConfig? _popPage() {
if (!_canPopPage()) return null;
return _doPopPage();
}
GetNavConfig? _pop(PopMode mode) {
switch (mode) {
case PopMode.History:
return _popHistory();
case PopMode.Page:
return _popPage();
default:
return null;
}
}
// returns the popped page
GetNavConfig? _doPopPage() {
final currentBranch = currentConfiguration?.currentTreeBranch;
if (currentBranch != null && currentBranch.length > 1) {
//remove last part only
final remaining = currentBranch.take(currentBranch.length - 1);
final prevHistoryEntry =
history.length > 1 ? history[history.length - 2] : null;
//check if current route is the same as the previous route
if (prevHistoryEntry != null) {
//if so, pop the entire history entry
final newLocation = remaining.last.name;
final prevLocation = prevHistoryEntry.location;
if (newLocation == prevLocation) {
//pop the entire history entry
return _popHistory();
}
}
//create a new route with the remaining tree branch
final res = _popHistory();
_pushHistory(
GetNavConfig(
currentTreeBranch: remaining.toList(),
location: remaining.last.name,
state: null, //TOOD: persist state??
),
);
return res;
} else {
//remove entire entry
return _popHistory();
}
}
Future<GetNavConfig?> popHistory() {
return SynchronousFuture(_popHistory());
}
bool _canPopHistory() {
return history.length > 1;
}
Future<bool> canPopHistory() {
return SynchronousFuture(_canPopHistory());
}
bool _canPopPage() {
final currentTreeBranch = currentConfiguration?.currentTreeBranch;
if (currentTreeBranch == null) return false;
return currentTreeBranch.length > 1 ? true : _canPopHistory();
}
Future<bool> canPopPage() {
return SynchronousFuture(_canPopPage());
}
bool _canPop(PopMode mode) {
switch (mode) {
case PopMode.History:
return _canPopHistory();
case PopMode.Page:
default:
return _canPopPage();
}
}
/// gets the visual pages from the current history entry
///
/// visual pages must have the [RouterOutletContainerMiddleWare] middleware
/// with `stayAt` equal to the route name of the visual page
List<GetPage> getVisualPages() {
final currentHistory = currentConfiguration;
if (currentHistory == null) return <GetPage>[];
return currentHistory.currentTreeBranch.where((r) {
final mware =
(r.middlewares ?? []).whereType<RouterOutletContainerMiddleWare>();
if (mware.length == 0) return true;
return r.name == mware.first.stayAt;
}).toList();
}
@override
Widget build(BuildContext context) {
final pages = getVisualPages();
final extraObservers = navigatorObservers;
return Navigator(
key: navigatorKey,
onPopPage: _onPopVisualRoute,
pages: pages,
observers: [
GetObserver(),
if (extraObservers != null) ...extraObservers,
],
transitionDelegate:
transitionDelegate ?? const DefaultTransitionDelegate<dynamic>(),
);
}
@override
Future<void> setInitialRoutePath(GetNavConfig configuration) async {
history.clear();
_resultCompleter.clear();
await pushHistory(configuration);
}
@override
Future<void> setNewRoutePath(GetNavConfig configuration) async {
await pushHistory(configuration);
}
@override
GetNavConfig? get currentConfiguration {
if (history.isEmpty) return null;
final route = history.last;
return route;
}
Future<T?> toNamed<T>(String fullRoute) {
final decoder = Get.routeTree.matchRoute(fullRoute);
return pushHistory<T>(
GetNavConfig(
currentTreeBranch: decoder.treeBranch,
location: fullRoute,
state: null, //TODO: persist state?
),
);
}
/// Removes routes according to [PopMode]
/// until it reaches the specifc [fullRoute],
/// DOES NOT remove the [fullRoute]
void until(
String fullRoute, {
PopMode popMode = PopMode.Page,
}) {
// remove history or page entries until you meet route
var iterator = currentConfiguration;
while (_canPop(popMode) &&
iterator != null &&
iterator.location != fullRoute) {
_pop(popMode);
// replace iterator
iterator = currentConfiguration;
}
refresh();
}
GetPage _notFound() {
return notFoundRoute ??= GetPage(
name: '/404',
page: () => Scaffold(
body: Text('not found'),
),
);
}
Future<bool> handlePopupRoutes({
Object? result,
}) async {
Route? currentRoute;
navigatorKey.currentState!.popUntil((route) {
currentRoute = route;
return true;
});
if (currentRoute is PopupRoute) {
return await navigatorKey.currentState!.maybePop(result);
}
return false;
}
@override
Future<bool> popRoute({
Object? result,
PopMode popMode = PopMode.Page,
}) async {
//Returning false will cause the entire app to be popped.
final wasPopup = await handlePopupRoutes(result: result);
if (wasPopup) return true;
final _popped = _pop(popMode);
refresh();
if (_popped != null) {
//emulate the old pop with result
final lastCompleter = _resultCompleter.remove(_popped);
lastCompleter?.complete(result);
return Future.value(true);
}
return Future.value(false);
}
bool _onPopVisualRoute(Route<dynamic> route, dynamic result) {
final didPop = route.didPop(result);
if (!didPop) {
return false;
}
final settings = route.settings;
if (settings is GetPage) {
final config = history.cast<GetNavConfig?>().firstWhere(
(element) => element?.currentPage == settings,
orElse: () => null,
);
if (config != null) {
_removeHistoryEntry(config);
}
}
refresh();
return true;
}
}