Applied more Riverpod best practices

This commit is contained in:
venir.dev
2022-12-31 01:01:56 +01:00
parent 599b66417b
commit f447c93fc2
3 changed files with 14 additions and 18 deletions

View File

@ -43,7 +43,7 @@ class HomePage extends ConsumerWidget {
const Text("Home Page"),
ElevatedButton(
onPressed: () {
ref.read(authNotifierProvider.notifier).logout();
ref.watch(authNotifierProvider.notifier).logout();
},
child: const Text("Logout"),
),
@ -69,7 +69,7 @@ class LoginPage extends ConsumerWidget {
const Text("Login Page"),
ElevatedButton(
onPressed: () async {
ref.read(authNotifierProvider.notifier).login(
ref.watch(authNotifierProvider.notifier).login(
"myEmail",
"myPassword",
);

View File

@ -33,30 +33,26 @@ class HomeRoute extends GoRouteData {
FutureOr<String?> redirect(BuildContext context, GoRouterState state) async {
if (state.location == HomeRoute.path) return null;
final asyncRole =
ProviderScope.containerOf(context).read(permissionsProvider);
final roleListener = ProviderScope.containerOf(context).listen(
permissionsProvider.select((value) => value.valueOrNull),
(previous, next) {},
);
final userRole = asyncRole.valueOrNull;
if (userRole == null) return HomeRoute.path;
return userRole.map(
final userRole = roleListener.read();
final redirectTo = userRole?.maybeMap(
admin: (_) => null,
user: (_) {
if (state.location == AdminRoute.path) return HomeRoute.path;
return null;
},
guest: (_) {
if (state.location == AdminRoute.path ||
state.location == UserRoute.path) {
return HomeRoute.path;
}
return null;
},
none: (_) {
orElse: () {
if (state.location != HomeRoute.path) return HomeRoute.path;
return null;
},
);
roleListener.close();
return redirectTo;
}
@override

View File

@ -44,7 +44,7 @@ class HomePage extends ConsumerWidget {
const Text("Home Page"),
ElevatedButton(
onPressed: () {
ref.read(authNotifierProvider.notifier).logout();
ref.watch(authNotifierProvider.notifier).logout();
},
child: const Text("Logout"),
),
@ -71,7 +71,7 @@ class LoginPage extends ConsumerWidget {
const Text("Login Page"),
ElevatedButton(
onPressed: () async {
ref.read(authNotifierProvider.notifier).login(
ref.watch(authNotifierProvider.notifier).login(
"myEmail",
"myPassword",
);