-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app_router.dart
582 lines (537 loc) · 18.8 KB
/
app_router.dart
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
part of katana_router;
/// {@template katana_router.app_router}
/// Controller to define routing for the entire app.
///
/// You can define the routing for the entire app by passing it to `routerConfig` in [MaterialApp.router].
///
/// The controller itself can also be manipulated, and page transitions can be performed directly by executing [push], [replace], and [pop].
///
/// It is also possible to get the [AppRouter] object itself with [AppRouter.of].
///
/// By executing [setPathUrlStrategy], it is possible to use URLs with the web hash (#) removed.
///
/// Adapters for loggers can be applied to routing in [loggerAdapters].
///
/// アプリ全体のルーティングを定義するためのコントローラー。
///
/// [MaterialApp.router]の`routerConfig`に渡すことでアプリ全体のルーティングを定義することができます。
///
/// また、このコントローラー自体を操作することが可能で[push]や[replace]、[pop]を実行することでページ遷移を直接行うことが可能です。
///
/// また、[AppRouter.of]で[AppRouter]のオブジェクト自体を取得することも可能です。
///
/// [setPathUrlStrategy]を実行することでWebのハッシュ(#)を消したURLを利用することが可能になります。
///
/// [loggerAdapters]でロガー用のアダプターをルーティングに適用することができます。
///
/// ```dart
/// final appRouter = AppRouter(
/// pages: [
/// ListPage.query,
/// DetailPage.query,
/// ]
/// );
///
/// void main(){
/// runApp(
/// const MainPage(),
/// );
/// }
///
/// class MainPage extends StatelessWidget {
/// const MainPage();
///
/// @override
/// Widget build(BuilcContext context){
/// return MaterialApp.router(
/// routerConfig: appRouter,
/// title: "Title",
/// );
/// }
/// }
///
/// ```
/// {@endtemplate}
class AppRouter extends ChangeNotifier
with NavigatorObserver
implements RouterConfig<RouteQuery> {
/// {@template katana_router.app_router}
/// Controller to define routing for the entire app.
///
/// You can define the routing for the entire app by passing it to `routerConfig` in [MaterialApp.router].
///
/// The controller itself can also be manipulated, and page transitions can be performed directly by executing [push], [replace], and [pop].
///
/// It is also possible to get the [AppRouter] object itself with [AppRouter.of].
///
/// By executing [setPathUrlStrategy], it is possible to use URLs with the web hash (#) removed.
///
/// Adapters for loggers can be applied to routing in [loggerAdapters].
///
/// アプリ全体のルーティングを定義するためのコントローラー。
///
/// [MaterialApp.router]の`routerConfig`に渡すことでアプリ全体のルーティングを定義することができます。
///
/// また、このコントローラー自体を操作することが可能で[push]や[replace]、[pop]を実行することでページ遷移を直接行うことが可能です。
///
/// また、[AppRouter.of]で[AppRouter]のオブジェクト自体を取得することも可能です。
///
/// [setPathUrlStrategy]を実行することでWebのハッシュ(#)を消したURLを利用することが可能になります。
///
/// [loggerAdapters]でロガー用のアダプターをルーティングに適用することができます。
///
/// ```dart
/// final appRouter = AppRouter(
/// pages: [
/// ListPage.query,
/// DetailPage.query,
/// ]
/// );
///
/// void main(){
/// runApp(
/// const MainPage(),
/// );
/// }
///
/// class MainPage extends StatelessWidget {
/// const MainPage();
///
/// @override
/// Widget build(BuilcContext context){
/// return MaterialApp.router(
/// routerConfig: appRouter,
/// title: "Title",
/// );
/// }
/// }
///
/// ```
/// {@endtemplate}
AppRouter({
UnknownRouteQueryBuilder? unknown,
BootRouteQueryBuilder? boot,
String? initialPath,
RouteQuery? initialQuery,
required List<RouteQueryBuilder> pages,
List<RedirectQuery> redirect = const [],
List<NavigatorObserver> observers = const [],
int redirectLimit = 5,
GlobalKey<NavigatorState>? navigatorKey,
String? restorationScopeId,
TransitionQuery? defaultTransitionQuery,
bool reportsRouteUpdateToEngine = true,
Widget backgroundWidget = const Scaffold(),
List<LoggerAdapter> loggerAdapters = const [],
bool nested = false,
}) : _loggerAdapters = loggerAdapters {
navigatorKey ??= GlobalKey<NavigatorState>();
_config = _AppRouterConfig(
pages: pages,
redirect: redirect,
boot: boot,
unknown: unknown,
navigatorKey: navigatorKey,
redirectLimite: redirectLimit,
defaultTransitionQuery: defaultTransitionQuery,
reportsRouteUpdateToEngine: reportsRouteUpdateToEngine,
backgroundWidget: backgroundWidget,
nested: nested,
);
_routerDelegate = _AppRouterDelegate(
router: this,
observers: [this, ...observers],
restorationScopeId: restorationScopeId,
);
_routeInformationParser = _AppRouteInformationParser(this);
nested = nested || initialQuery?.nested == true;
final effectiveInitialLocation = nested
? null
: _effectiveInitialLocation(
initialPath,
);
_routeInformationProvider = _AppRouteInformationProvider(
router: this,
initialRouteInformation: InitialRouteInformation(
query: nested
? initialQuery
: _effectiveInitialQuery(
effectiveInitialLocation,
initialQuery,
),
location: effectiveInitialLocation,
),
);
}
late final _AppRouterConfig _config;
final List<_PageStackContainer> _pageStack = [];
/// Adapter to define loggers.
///
/// ロガーを定義するアダプター。
List<LoggerAdapter> get loggerAdapters {
return [...LoggerAdapter.primary, ..._loggerAdapters];
}
final List<LoggerAdapter> _loggerAdapters;
BuildContext? get _context => _config.navigatorKey.currentContext;
/// List of [NavigatorObserver] currently owned by [AppRouter].
///
/// [AppRouter]が現在持っている[NavigatorObserver]の一覧。
List<NavigatorObserver> get navigatorObservers => _routerDelegate.observers;
@override
RouterDelegate<RouteQuery> get routerDelegate => _routerDelegate;
late final _AppRouterDelegate _routerDelegate;
@override
RouteInformationParser<RouteQuery> get routeInformationParser =>
_routeInformationParser;
late final _AppRouteInformationParser _routeInformationParser;
@override
final BackButtonDispatcher backButtonDispatcher = RootBackButtonDispatcher();
@override
RouteInformationProvider? get routeInformationProvider =>
_routeInformationProvider;
late final _AppRouteInformationProvider _routeInformationProvider;
/// List of pages currently passed to [AppRouter].
///
/// 現在[AppRouter]に渡されているページのリスト。
List<RouteQueryBuilder> get pages => _config.pages;
/// You can check the current [RouteQuery].
///
/// 現在の[RouteQuery]を確認することができます。
RouteQuery? get currentQuery => _routerDelegate.currentConfiguration;
/// Passing [routeQuery] will take you to a new page.
///
/// The method of page transition can be specified with [transitionQuery].
///
/// You can wait until the page is destroyed by the [pop] method with the return value [Future].
///
/// In doing so, it can also receive the object passed by [pop].
///
/// [routeQuery]を渡すことにより新しいページに遷移します。
///
/// ページ遷移の方法を[transitionQuery]で指定可能です。
///
/// 戻り値の[Future]で[pop]メソッドでページが破棄されるまで待つことができます。
///
/// また、その際[pop]で渡されたオブジェクトを受け取ることができます。
Future<E?> push<E>(
RouteQuery routeQuery, [
TransitionQuery? transitionQuery,
]) async {
final completer = Completer<E?>();
final resolveQuery = _InnerRouteQueryImpl(
routeQuery: _context != null
? await _redirect(_context!, routeQuery)
: routeQuery,
transitionQuery: transitionQuery ?? _config.defaultTransitionQuery,
);
_pageStack.add(
_PageStackContainer<E>(
query: resolveQuery,
route: resolveQuery.route<E>(),
completer: completer,
),
);
_routerDelegate.notifyListeners();
return completer.future;
}
/// Passing [routeQuery] replaces the currently displayed page with a new page.
///
/// The method of page transition can be specified with [transitionQuery].
///
/// You can wait until the page is destroyed by the [pop] method with the return value [Future].
///
/// In doing so, it can also receive the object passed by [pop].
///
/// [routeQuery]を渡すことにより現在表示されているページを新しいページに置き換えます。
///
/// ページ遷移の方法を[transitionQuery]で指定可能です。
///
/// 戻り値の[Future]で[pop]メソッドでページが破棄されるまで待つことができます。
///
/// また、その際[pop]で渡されたオブジェクトを受け取ることができます。
Future<E?> replace<E>(
RouteQuery routeQuery, [
TransitionQuery? transitionQuery,
]) {
pop();
return push<E>(routeQuery, transitionQuery);
}
/// Checks if the page is [pop]-able. If `true` is returned, the page is [pop]able.
///
/// ページが[pop]可能かどうかをチェックします。`true`が返された場合[pop]可能です。
bool canPop() => _pageStack.isNotEmpty;
/// Discards the current page and returns to the previous page.
///
/// If [canPop] is `false`, the application is terminated.
///
/// By passing a value to [result], an object can be passed to the return value of [push] or [replace].
///
/// 現在のページを破棄し、前のページに戻ります。
///
/// [canPop]が`false`の場合、アプリを終了します。
///
/// [result]に値を渡すことにより[push]や[replace]の戻り値にオブジェクトを渡すことができます。
void pop<E>([E? result]) {
if (!canPop()) {
SystemNavigator.pop();
return;
}
final container = _pageStack.removeLast();
container.completer.complete(result);
_routerDelegate.notifyListeners();
}
/// Keep [pop] until the [predicate] condition is `true`.
///
/// The result of [pop] is returned by [result].
///
/// [predicate]の条件が`true`になるまで[pop]し続けます。
///
/// [pop]した結果を[result]で返します。
void popUntil<E>(bool Function(RouteQuery query) predicate, [E? result]) {
var index = _pageStack.length - 1;
while (index >= 0 && !predicate(_pageStack[index].query)) {
final container = _pageStack.removeAt(index);
container.completer.complete(result);
index -= 1;
}
_routerDelegate.notifyListeners();
}
/// Continue to [pop] until the history stack runs out.
///
/// The result of [pop] is returned by [result].
///
/// ヒストリーのスタックがなくなるまで[pop]し続けます。
///
/// [pop]した結果を[result]で返します。
void reset<E>([E? result]) {
var index = _pageStack.length - 1;
while (index >= 0) {
final container = _pageStack.removeAt(index);
container.completer.complete(result);
index -= 1;
}
_routerDelegate.notifyListeners();
}
/// Keep [pop] until the history stack runs out, then [push] [routeQuery].
///
/// The method of page transition can be specified with [transitionQuery].
///
/// ヒストリーのスタックがなくなるまで[pop]し続けた後[routeQuery]を[push]します。
///
/// ページ遷移の方法を[transitionQuery]で指定可能です。
Future<E?> resetAndPush<E>(
RouteQuery routeQuery, [
TransitionQuery? transitionQuery,
]) {
var index = _pageStack.length - 1;
while (index >= 0) {
final container = _pageStack.removeAt(index);
container.completer.complete(null);
index -= 1;
}
return push<E>(routeQuery, transitionQuery);
}
/// Refresh the current page.
///
/// 現在のページを再更新します。
void refresh() {
_routeInformationProvider.notifyListeners();
}
/// Sets the URL strategy of your web app to using paths instead of a leading hash (#).
///
/// You can safely call this on all platforms, i.e. also when running on mobile or desktop. In that case, it will simply be a noop.
///
/// Web アプリの URL 戦略を、先頭のハッシュ (#) の代わりにパスを使用するように設定します。
///
/// これは、すべてのプラットフォームで安全に呼び出すことができます。つまり、モバイルまたはデスクトップで実行している場合でも同様です。その場合、それは単にヌープになります。
static void setPathUrlStrategy() => url_strategy.setPathUrlStrategy();
/// Get [AppRouter] placed on the widget tree.
///
/// Setting [root] to `true` will get [AppRouter] at the top level.
///
/// ウィジェットツリー上に配置されている[AppRouter]を取得します。
///
/// [root]を`true`にすると最上位にある[AppRouter]を取得します。
static AppRouter of(BuildContext context, {bool root = false}) {
final navigator = Navigator.of(context, rootNavigator: root).context;
final scope = navigator
.getElementForInheritedWidgetOfExactType<AppRouteScope>()
?.widget as AppRouteScope?;
assert(scope != null, "AppRouter is not found.");
return scope!.router;
}
FutureOr<RouteQuery> _redirect(
BuildContext context,
RouteQuery query,
) async {
final redirectList = [
...query.redirect(),
..._config.redirect,
];
for (final r in redirectList) {
final res = await r.redirect(context, query);
if (res != null) {
return res;
}
}
return query;
}
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_sendLog(RouteLoggerEvent.push, parameters: {
RouteLoggerEvent.newRouteKey: route.settings.name,
RouteLoggerEvent.prevRouteKey: previousRoute?.settings.name,
});
notifyListeners();
});
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_sendLog(RouteLoggerEvent.pop, parameters: {
RouteLoggerEvent.newRouteKey: previousRoute?.settings.name,
RouteLoggerEvent.prevRouteKey: route.settings.name,
});
notifyListeners();
});
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
WidgetsBinding.instance.addPostFrameCallback((_) {
notifyListeners();
});
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_sendLog(RouteLoggerEvent.pop, parameters: {
RouteLoggerEvent.newRouteKey: newRoute?.settings.name,
RouteLoggerEvent.prevRouteKey: oldRoute?.settings.name,
});
notifyListeners();
});
}
@override
void dispose() {
_routeInformationProvider.dispose();
_routerDelegate.dispose();
super.dispose();
}
void _sendLog(RouteLoggerEvent event, {DynamicMap? parameters}) {
for (final loggerAdapter in loggerAdapters) {
loggerAdapter.send(event.toString(), parameters: parameters);
}
}
String? _effectiveInitialLocation(String? initialLocation) {
final String platformDefault =
WidgetsBinding.instance.platformDispatcher.defaultRouteName;
if (platformDefault == "/") {
return initialLocation;
} else {
return platformDefault;
}
}
RouteQuery? _effectiveInitialQuery(
String? initialLocation,
RouteQuery? initialQuery,
) {
if (initialLocation.isEmpty) {
return initialQuery;
}
for (final page in _config.pages) {
final query = page.resolve(initialLocation);
if (query != null) {
return query;
}
}
return initialQuery;
}
}
/// Class for creating nested [AppRouter].
///
/// ネストされた[AppRouter]を作成するためのクラスです。
///
/// {@macro katana_router.app_router}
class NestedAppRouter extends AppRouter {
/// Class for creating nested [AppRouter].
///
/// ネストされた[AppRouter]を作成するためのクラスです。
///
/// {@macro katana_router.app_router}
NestedAppRouter({
super.unknown,
super.boot,
super.initialPath,
super.initialQuery,
required super.pages,
super.redirect = const [],
super.observers = const [],
super.redirectLimit = 5,
super.navigatorKey,
super.restorationScopeId,
super.defaultTransitionQuery,
super.reportsRouteUpdateToEngine = true,
super.backgroundWidget = const Scaffold(),
super.loggerAdapters = const [],
}) : super(nested: true);
}
/// [InheritedWidget] for placing [AppRouter] on the widget tree.
///
/// You can take the value of [AppRouter] passed here in [AppRouter.of].
///
/// [AppRouter]をウィジェットツリー上に配置するための[InheritedWidget]。
///
/// [AppRouter.of]でここで渡した[AppRouter]の値を取ることができます。
@immutable
class AppRouteScope extends InheritedWidget {
const AppRouteScope({
super.key,
required this.router,
required super.child,
});
/// Value of [AppRouter].
///
/// [AppRouter]の値。
final AppRouter router;
@override
bool updateShouldNotify(covariant AppRouteScope oldWidget) {
return false;
}
}
@immutable
class _PageStackContainer<T> {
const _PageStackContainer({
required this.query,
required this.route,
required this.completer,
});
final AppPageRoute<T> route;
final RouteQuery query;
final Completer<T?> completer;
}
@immutable
class _AppRouterConfig {
const _AppRouterConfig({
this.boot,
this.unknown,
this.pages = const [],
this.redirect = const [],
this.redirectLimite = 5,
required this.navigatorKey,
this.defaultTransitionQuery,
this.backgroundWidget = const Scaffold(),
this.reportsRouteUpdateToEngine = true,
this.nested = false,
});
final bool nested;
final BootRouteQueryBuilder? boot;
final UnknownRouteQueryBuilder? unknown;
final List<RouteQueryBuilder> pages;
final List<RedirectQuery> redirect;
final int redirectLimite;
final GlobalKey<NavigatorState> navigatorKey;
final TransitionQuery? defaultTransitionQuery;
final bool reportsRouteUpdateToEngine;
final Widget backgroundWidget;
}