Files
recipe-app/flutter/lib/core/router/app_router.dart
T

65 lines
1.9 KiB
Dart

import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/ui/app_shell.dart';
import '../../features/auth/data/auth_providers.dart';
import '../../features/recipes/presentation/recipes_screen.dart';
import '../../features/auth/presentation/login_screen.dart';
import '../../features/profile/presentation/profile_screen.dart';
final appRouterProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authStateProvider);
return GoRouter(
initialLocation: '/',
redirect: (context, state) {
final isLoading = authState.isLoading;
final token = authState.valueOrNull;
final isLoggedIn = token != null && token.isNotEmpty;
final isLoginRoute = state.matchedLocation == '/login';
final isRootRoute = state.matchedLocation == '/';
if (isLoading) {
return null;
}
if (isRootRoute) {
return isLoggedIn ? '/recipes' : '/login';
}
if (!isLoggedIn && !isLoginRoute) {
return '/login';
}
if (isLoggedIn && isLoginRoute) {
return '/recipes';
}
return null;
},
routes: [
GoRoute(path: '/', builder: (context, state) => const SizedBox.shrink()),
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
ShellRoute(
builder: (context, state, child) {
return AppShell(location: state.uri.path, child: child);
},
routes: [
GoRoute(
path: '/recipes',
builder: (context, state) => const RecipesScreen(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
);
});