-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathrouter.dart
More file actions
48 lines (39 loc) · 1.29 KB
/
router.dart
File metadata and controls
48 lines (39 loc) · 1.29 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
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider;
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'screens/counter/screen.dart';
import 'screens/login.dart';
final router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(path: '/', builder: (context, state) => const CounterScreen()),
GoRoute(path: '/login', builder: (context, state) => const LoginScreen()),
],
redirect: (context, state) async {
// Ensure we capture the redirect result before checking the auth state.
await FirebaseAuth.instance.getRedirectResult();
final loggedIn = FirebaseAuth.instance.currentUser != null;
final loggingIn = state.matchedLocation == '/login';
if (!loggedIn) return '/login';
if (loggingIn) return '/';
return null;
},
refreshListenable: GoRouterRefreshStream(
FirebaseAuth.instance.authStateChanges(),
),
);
class GoRouterRefreshStream extends ChangeNotifier {
GoRouterRefreshStream(Stream<dynamic> stream) {
notifyListeners();
_subscription = stream.asBroadcastStream().listen(
(dynamic _) => notifyListeners(),
);
}
late final StreamSubscription<dynamic> _subscription;
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
}