-
Notifications
You must be signed in to change notification settings - Fork 34
/
router_notifier.dart
93 lines (90 loc) · 3.01 KB
/
router_notifier.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
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:devtodollars/components/dialog_page.dart';
import 'package:devtodollars/components/reset_password_dialog.dart';
import 'package:devtodollars/screens/auth_screen.dart';
import 'package:devtodollars/screens/home_screen.dart';
import 'package:devtodollars/screens/payments_screen.dart';
import 'package:devtodollars/services/auth_notifier.dart';
part 'router_notifier.g.dart';
// This is crucial for making sure that the same navigator is used
// when rebuilding the GoRouter and not throwing away the whole widget tree.
final navigatorKey = GlobalKey<NavigatorState>();
Uri? initUrl = Uri.base; // needed to set intiial url state
@riverpod
GoRouter router(RouterRef ref) {
final authState = ref.watch(authProvider);
return GoRouter(
initialLocation: initUrl?.path, // DO NOT REMOVE
navigatorKey: navigatorKey,
observers: [PosthogObserver()],
redirect: (context, state) async {
return authState.when(
data: (user) {
// build initial path
String? path = initUrl?.path;
final queryString = initUrl?.query.trim() ?? "";
if (queryString.isNotEmpty && path != null) {
path += "?$queryString";
}
// If user is not authenticated, direct to login screen
if (user == null && initUrl?.path != '/login') {
return '/login';
}
// If user is authenticated and trying to access login or loading, direct to home
if (user != null &&
(initUrl?.path == '/login' || initUrl?.path == '/loading')) {
return "/";
}
// After handling initial redirection, clear initUrl to prevent repeated redirections
initUrl = null;
return path;
},
error: (_, __) => "/loading",
loading: () => "/loading",
);
},
routes: <RouteBase>[
GoRoute(
name: 'loading',
path: '/loading',
builder: (context, state) {
return const Center(child: CircularProgressIndicator());
},
),
GoRoute(
name: 'login',
path: '/login',
builder: (context, state) {
return const AuthScreen();
},
),
GoRoute(
name: 'home',
path: '/',
builder: (context, state) {
return const HomeScreen(title: "DevToDollars");
},
routes: [
GoRoute(
name: 'reset',
path: 'reset',
pageBuilder: (_, __) {
return const DialogPage(child: ResetPasswordDialog());
},
)
],
),
GoRoute(
name: 'payments',
path: '/payments',
builder: (BuildContext context, GoRouterState state) {
final qp = state.uri.queryParameters;
return PaymentsScreen(price: qp["price"]);
},
),
],
);
}