Forked from Zambrella/beam_riverpod_authentication.dart
Created
April 19, 2022 00:52
-
-
Save light9/92adf2d6bf8584e3fdac9a04b98a5cbb to your computer and use it in GitHub Desktop.
Beamer + Riverpod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() async { | |
WidgetsFlutterBinding.ensureInitialized(); | |
final container = ProviderContainer(); | |
final routerDelegate = createDelegate(container.read); | |
final routeInformationParser = BeamerParser(); | |
F.appFlavor = Flavor.DEV; | |
await Firebase.initializeApp(); | |
runApp( | |
UncontrolledProviderScope( | |
container: container, | |
child: BeamerProvider( | |
routerDelegate: routerDelegate, | |
child: App( | |
routeInformationParser, | |
routerDelegate, | |
), | |
), | |
), | |
); | |
} | |
BeamerDelegate createDelegate(Reader read) { | |
return BeamerDelegate( | |
initialPath: '/home', | |
locationBuilder: BeamerLocationBuilder( | |
beamLocations: [ | |
AuthenticationLocation(), | |
HomeLocation(), | |
], | |
), | |
guards: [ | |
BeamGuard( | |
pathPatterns: ['/login', '/register', '/forgot_password'], | |
guardNonMatching: true, | |
check: (_, __) => read(authenticationListenerProvider), | |
beamToNamed: '/login'), | |
], | |
); | |
} | |
class App extends ConsumerWidget { | |
const App(this.routeInformationParser, this.routerDelegate, {Key? key}) : super(key: key); | |
final RouteInformationParser<Object> routeInformationParser; | |
final BeamerDelegate routerDelegate; | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
//* Authentication listener | |
ref.listen(authenticationListenerProvider, (bool isLoggedIn) { | |
if (isLoggedIn) { | |
context.beamTo(HomeLocation()); | |
} else { | |
context.beamTo(AuthenticationLocation()); | |
} | |
}); | |
return MaterialApp.router( | |
routeInformationParser: routeInformationParser, | |
routerDelegate: routerDelegate, | |
title: F.title, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
); | |
} | |
} | |
class AuthenticationNotifier extends StateNotifier<bool> { | |
AuthenticationNotifier(this._authenticationRepository) : super(false) { | |
_authenticationRepository.getUser().listen((user) { | |
if (user.uid == null) { | |
state = false; | |
} else { | |
state = true; | |
} | |
}); | |
} | |
final AuthenticationRepository _authenticationRepository; | |
late final StreamSubscription<User?> _userSubscription; | |
@override | |
void dispose() { | |
_userSubscription.cancel(); | |
super.dispose(); | |
} | |
} | |
final authenticationListenerProvider = StateNotifierProvider<AuthenticationNotifier, bool>( | |
(ref) => AuthenticationNotifier(ref.watch(authenticationRepositoryProvider)), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment