83 lines
2.8 KiB
Dart
83 lines
2.8 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flux/core/blocs/session/session_bloc.dart';
|
|
import 'package:flux/features/auth/ui/auth_screen.dart';
|
|
import 'package:flux/features/company/ui/create_company_screen.dart';
|
|
import 'package:flux/features/dashboard/ui/dashboard_screen.dart';
|
|
import 'package:flux/features/store/ui/create_store_screen.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'dart:async';
|
|
|
|
class AppRouter {
|
|
// Funzione statica per creare il router
|
|
static GoRouter createRouter(SessionBloc sessionBloc) {
|
|
return GoRouter(
|
|
initialLocation: '/',
|
|
// Ascolta i cambiamenti del Bloc per scatenare il redirect
|
|
refreshListenable: _GoRouterRefreshStream(sessionBloc.stream),
|
|
redirect: (context, state) {
|
|
final sessionState = sessionBloc.state;
|
|
|
|
// Logica di redirezione basata sugli stati del SessionBloc
|
|
final bool isUnknown = sessionState.status == SessionStatus.unknown;
|
|
final bool isUnauthenticated =
|
|
sessionState.status == SessionStatus.unauthenticated;
|
|
final bool isNoCompany =
|
|
sessionState.status == SessionStatus.authenticatedNoCompany;
|
|
final bool isNoStore =
|
|
sessionState.status == SessionStatus.authenticatedNoStore;
|
|
final bool isReady = sessionState.status == SessionStatus.ready;
|
|
|
|
final String location = state.matchedLocation;
|
|
|
|
if (isUnknown) return null; // Aspetta che l'app si svegli
|
|
|
|
if (isUnauthenticated && location != '/login') return '/login';
|
|
|
|
if (isNoCompany && location != '/create-company')
|
|
return '/create-company';
|
|
|
|
if (isNoStore && location != '/create-store') return '/create-store';
|
|
|
|
// Se sono loggato e sto cercando di andare alla login, vai in dashboard
|
|
if (isReady && location == '/login') return '/';
|
|
|
|
return null;
|
|
},
|
|
routes: [
|
|
GoRoute(
|
|
path: '/',
|
|
builder: (context, state) => const DashboardScreen(),
|
|
),
|
|
GoRoute(
|
|
path: '/login',
|
|
builder: (context, state) => const AuthScreen(),
|
|
),
|
|
GoRoute(
|
|
path: '/create-company',
|
|
builder: (context, state) => const CreateCompanyScreen(),
|
|
),
|
|
GoRoute(
|
|
path: '/create-store',
|
|
builder: (context, state) => const CreateStoreScreen(),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
}
|
|
|
|
// Classe di supporto per convertire lo Stream del Bloc in un Listenable per GoRouter
|
|
class _GoRouterRefreshStream extends ChangeNotifier {
|
|
_GoRouterRefreshStream(Stream<dynamic> stream) {
|
|
notifyListeners();
|
|
_subscription = stream.asBroadcastStream().listen((_) => notifyListeners());
|
|
}
|
|
|
|
late final StreamSubscription<dynamic> _subscription;
|
|
|
|
@override
|
|
void dispose() {
|
|
_subscription.cancel();
|
|
super.dispose();
|
|
}
|
|
}
|