Skip to content

Instantly share code, notes, and snippets.

@Zambrella
Created October 26, 2021 19:32
Show Gist options
  • Save Zambrella/73486d027fa0186d4e8ea7ccb11a5079 to your computer and use it in GitHub Desktop.
Save Zambrella/73486d027fa0186d4e8ea7ccb11a5079 to your computer and use it in GitHub Desktop.
Beamer + Riverpod
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