65 lines
2.0 KiB
Dart
65 lines
2.0 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
|
|
import 'package:real_estate_mobile/features/auth/presentation/screens/login_screen.dart';
|
|
import 'package:real_estate_mobile/features/auth/presentation/screens/signup_screen.dart';
|
|
import 'package:real_estate_mobile/features/home/presentation/screens/home_screen.dart';
|
|
|
|
final routerProvider = Provider<GoRouter>((ref) {
|
|
final authRefreshNotifier = _AuthRefreshNotifier();
|
|
|
|
ref.listen(authProvider, (_, __) {
|
|
authRefreshNotifier.notify();
|
|
});
|
|
|
|
ref.onDispose(() {
|
|
authRefreshNotifier.dispose();
|
|
});
|
|
|
|
return GoRouter(
|
|
initialLocation: '/login',
|
|
refreshListenable: authRefreshNotifier,
|
|
redirect: (context, state) {
|
|
final authState = ref.read(authProvider);
|
|
final isAuthenticated = authState.status == AuthStatus.authenticated;
|
|
final isLoading = authState.status == AuthStatus.loading;
|
|
|
|
final isAuthRoute = state.matchedLocation == '/login' ||
|
|
state.matchedLocation == '/signup';
|
|
|
|
// While checking auth status, don't redirect
|
|
if (isLoading) return null;
|
|
|
|
// If authenticated and on auth page, go to home
|
|
if (isAuthenticated && isAuthRoute) return '/home';
|
|
|
|
// If not authenticated and on protected page, go to login
|
|
if (!isAuthenticated && !isAuthRoute) return '/login';
|
|
|
|
return null;
|
|
},
|
|
routes: [
|
|
GoRoute(
|
|
path: '/login',
|
|
builder: (context, state) => const LoginScreen(),
|
|
),
|
|
GoRoute(
|
|
path: '/signup',
|
|
builder: (context, state) => const SignupScreen(),
|
|
),
|
|
GoRoute(
|
|
path: '/home',
|
|
builder: (context, state) => const HomeScreen(),
|
|
),
|
|
],
|
|
);
|
|
});
|
|
|
|
/// Notifier that triggers GoRouter refresh when auth state changes.
|
|
class _AuthRefreshNotifier extends ChangeNotifier {
|
|
void notify() {
|
|
notifyListeners();
|
|
}
|
|
}
|