refactor: migrate to go_router navigation

This commit is contained in:
cogwheel0
2025-09-22 14:36:43 +05:30
parent 462bf4cde2
commit 66a28958ed
11 changed files with 468 additions and 410 deletions

View File

@@ -0,0 +1,194 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../providers/app_providers.dart';
import '../services/navigation_service.dart';
import '../utils/debug_logger.dart';
import '../../features/auth/providers/unified_auth_providers.dart';
import '../../features/auth/views/authentication_page.dart';
import '../../features/auth/views/connect_signin_page.dart';
import '../../features/auth/views/server_connection_page.dart';
import '../../features/chat/views/chat_page.dart';
import '../../features/files/views/workspace_page.dart';
import '../../features/navigation/views/splash_launcher_page.dart';
import '../../features/profile/views/app_customization_page.dart';
import '../../features/profile/views/profile_page.dart';
import '../../l10n/app_localizations.dart';
import '../models/server_config.dart';
class RouterNotifier extends ChangeNotifier {
RouterNotifier(this.ref) {
_subscriptions = [
ref.listen<bool>(reviewerModeProvider, _onStateChanged),
ref.listen<AsyncValue<ServerConfig?>>(
activeServerProvider,
_onStateChanged,
),
ref.listen<AuthNavigationState>(
authNavigationStateProvider,
_onStateChanged,
),
];
}
final Ref ref;
late final List<ProviderSubscription<dynamic>> _subscriptions;
void _onStateChanged(dynamic previous, dynamic next) {
notifyListeners();
}
String? redirect(BuildContext context, GoRouterState state) {
final location = state.uri.path.isEmpty ? Routes.splash : state.uri.path;
final reviewerMode = ref.read(reviewerModeProvider);
final activeServerAsync = ref.read(activeServerProvider);
if (reviewerMode) {
if (location == Routes.chat) return null;
return Routes.chat;
}
if (activeServerAsync.isLoading) {
return location == Routes.splash ? null : Routes.splash;
}
if (activeServerAsync.hasError) {
return location == Routes.serverConnection
? null
: Routes.serverConnection;
}
final activeServer = activeServerAsync.asData?.value;
if (activeServer == null) {
if (_isAuthLocation(location)) return null;
return Routes.serverConnection;
}
final authState = ref.read(authNavigationStateProvider);
switch (authState) {
case AuthNavigationState.loading:
return location == Routes.splash ? null : Routes.splash;
case AuthNavigationState.needsLogin:
case AuthNavigationState.error:
if (_isAuthLocation(location)) return null;
return Routes.serverConnection;
case AuthNavigationState.authenticated:
if (_isAuthLocation(location) || location == Routes.splash) {
return Routes.chat;
}
return null;
}
}
bool _isAuthLocation(String location) {
return location == Routes.serverConnection ||
location == Routes.login ||
location == Routes.authentication;
}
@override
void dispose() {
for (final sub in _subscriptions) {
sub.close();
}
super.dispose();
}
}
final routerNotifierProvider = Provider<RouterNotifier>((ref) {
final notifier = RouterNotifier(ref);
ref.onDispose(notifier.dispose);
return notifier;
});
final goRouterProvider = Provider<GoRouter>((ref) {
final notifier = ref.watch(routerNotifierProvider);
final routes = <RouteBase>[
GoRoute(
path: Routes.splash,
name: RouteNames.splash,
builder: (context, state) => const SplashLauncherPage(),
),
GoRoute(
path: Routes.chat,
name: RouteNames.chat,
builder: (context, state) => const ChatPage(),
),
GoRoute(
path: Routes.login,
name: RouteNames.login,
builder: (context, state) => const ConnectAndSignInPage(),
),
GoRoute(
path: Routes.serverConnection,
name: RouteNames.serverConnection,
builder: (context, state) => const ServerConnectionPage(),
),
GoRoute(
path: Routes.authentication,
name: RouteNames.authentication,
builder: (context, state) {
final config = state.extra;
if (config is! ServerConfig) {
return const ServerConnectionPage();
}
return AuthenticationPage(serverConfig: config);
},
),
GoRoute(
path: Routes.profile,
name: RouteNames.profile,
builder: (context, state) => const ProfilePage(),
),
GoRoute(
path: Routes.appCustomization,
name: RouteNames.appCustomization,
builder: (context, state) => const AppCustomizationPage(),
),
GoRoute(
path: Routes.workspace,
name: RouteNames.workspace,
builder: (context, state) => const WorkspacePage(),
),
];
final router = GoRouter(
navigatorKey: NavigationService.navigatorKey,
initialLocation: Routes.splash,
refreshListenable: notifier,
redirect: notifier.redirect,
routes: routes,
observers: [NavigationLoggingObserver()],
errorBuilder: (context, state) {
final l10n = AppLocalizations.of(context);
final message =
l10n?.routeNotFound(state.uri.path) ??
'Route not found: ${state.uri.path}';
return Scaffold(
body: Center(child: Text(message, textAlign: TextAlign.center)),
);
},
);
NavigationService.attachRouter(router);
return router;
});
class NavigationLoggingObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
final previous = previousRoute?.settings.name ?? previousRoute?.settings;
DebugLogger.navigation(
'Pushed: ${route.settings.name ?? route.settings} (from ${previous ?? 'root'})',
);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
DebugLogger.navigation('Popped: ${route.settings.name ?? route.settings}');
}
}

View File

@@ -1,67 +1,70 @@
import 'package:flutter/material.dart';
// ThemedDialogs handles theming; no direct use of extensions here
import '../../features/auth/views/connect_signin_page.dart';
import '../../features/chat/views/chat_page.dart';
import '../../features/files/views/workspace_page.dart';
import '../../features/profile/views/profile_page.dart';
import 'package:go_router/go_router.dart';
import '../../shared/widgets/themed_dialogs.dart';
import 'package:conduit/l10n/app_localizations.dart';
/// Service for handling navigation throughout the app
/// Service for handling navigation throughout the app.
///
/// With GoRouter in place, this class mostly provides convenient wrappers
/// around the global router so existing callers can trigger navigation
/// without directly depending on BuildContext.
class NavigationService {
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
GlobalKey<NavigatorState>(debugLabel: 'rootNavigator');
static GoRouter? _router;
static GoRouter get router {
final router = _router;
if (router == null) {
throw StateError('GoRouter has not been attached to NavigationService.');
}
return router;
}
static void attachRouter(GoRouter router) {
_router = router;
}
static NavigatorState? get navigator => navigatorKey.currentState;
static BuildContext? get context => navigatorKey.currentContext;
static final List<String> _navigationStack = [];
static String? _currentRoute;
/// The current location reported by GoRouter.
static String? get currentRoute {
final router = _router;
if (router == null) return null;
return router.routeInformationProvider.value.uri.toString();
}
/// Get current route
static String? get currentRoute => _currentRoute;
/// Get navigation stack
static List<String> get navigationStack =>
List.unmodifiable(_navigationStack);
/// Navigate to a specific route
/// Navigate to a specific route path.
static Future<void> navigateTo(String routeName) async {
if (_currentRoute != routeName) {
_navigationStack.add(routeName);
_currentRoute = routeName;
}
final router = _router;
if (router == null) return;
router.go(routeName);
}
/// Navigate back with optional result
/// Navigate back with an optional result payload.
static void goBack<T>([T? result]) {
if (navigator?.canPop() == true) {
if (_navigationStack.isNotEmpty) {
_navigationStack.removeLast();
}
_currentRoute = _navigationStack.isNotEmpty
? _navigationStack.last
: null;
navigator?.pop<T>(result);
final router = _router;
if (router?.canPop() == true) {
router!.pop(result);
}
}
/// Check if can navigate back
static bool canGoBack() {
return navigator?.canPop() == true;
}
/// Check whether the router can pop the current route.
static bool canGoBack() => _router?.canPop() ?? false;
/// Show confirmation dialog before navigation
/// Show confirmation dialog before navigation.
static Future<bool> confirmNavigation({
required String title,
required String message,
String confirmText = 'Continue',
String cancelText = 'Cancel',
}) async {
if (context == null) return false;
final ctx = context;
if (ctx == null) return false;
final result = await ThemedDialogs.confirm(
context!,
ctx,
title: title,
message: message,
confirmText: confirmText,
@@ -72,95 +75,40 @@ class NavigationService {
return result;
}
/// Navigate to chat
static Future<void> navigateToChat() {
return navigateTo(Routes.chat);
}
static Future<void> navigateToChat() => navigateTo(Routes.chat);
static Future<void> navigateToLogin() => navigateTo(Routes.serverConnection);
static Future<void> navigateToProfile() => navigateTo(Routes.profile);
static Future<void> navigateToServerConnection() =>
navigateTo(Routes.serverConnection);
/// Navigate to login
static Future<void> navigateToLogin() {
return navigateTo(Routes.login);
}
/// Navigate to profile
static Future<void> navigateToProfile() {
return navigateTo(Routes.profile);
}
/// Navigate to server connection
static Future<void> navigateToServerConnection() {
return navigateTo(Routes.serverConnection);
}
// Chats list is now provided as a left drawer in ChatPage
/// Clear navigation stack (useful for logout)
/// Clear navigation history. With GoRouter this becomes a simple go call.
static void clearNavigationStack() {
_navigationStack.clear();
_currentRoute = null;
}
/// Set current route (useful for initial app state)
static void setCurrentRoute(String routeName) {
_currentRoute = routeName;
if (!_navigationStack.contains(routeName)) {
_navigationStack.add(routeName);
}
}
/// Generate routes
static Route<dynamic>? generateRoute(RouteSettings settings) {
Widget page;
switch (settings.name) {
// Removed tabbed main navigation
case Routes.chat:
page = const ChatPage();
break;
case Routes.login:
page = const ConnectAndSignInPage();
break;
case Routes.profile:
page = const ProfilePage();
break;
case Routes.serverConnection:
page = const ConnectAndSignInPage();
break;
case Routes.workspace:
page = const WorkspacePage();
break;
// chats list route removed (replaced by drawer)
// Removed navigation drawer route
default:
page = Builder(
builder: (context) => Scaffold(
body: Center(
child: Text(
AppLocalizations.of(context)!
.routeNotFound(settings.name ?? ''),
),
),
),
);
}
return MaterialPageRoute(builder: (_) => page, settings: settings);
final router = _router;
if (router == null) return;
router.go(Routes.serverConnection);
}
}
/// Route names
/// Route path definitions used across the app.
class Routes {
static const String splash = '/splash';
static const String chat = '/chat';
static const String login = '/login';
static const String profile = '/profile';
static const String serverConnection = '/server-connection';
static const String authentication = '/authentication';
static const String profile = '/profile';
static const String appCustomization = '/profile/customization';
static const String workspace = '/workspace';
}
/// Friendly names for GoRouter routes to support context.pushNamed.
class RouteNames {
static const String splash = 'splash';
static const String chat = 'chat';
static const String login = 'login';
static const String serverConnection = 'server-connection';
static const String authentication = 'authentication';
static const String profile = 'profile';
static const String appCustomization = 'app-customization';
static const String workspace = 'workspace';
}

View File

@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:conduit/l10n/app_localizations.dart';
import '../../shared/theme/theme_extensions.dart';
import 'navigation_service.dart';
/// User-friendly error messages and recovery actions
class UserFriendlyErrorHandler {
@@ -483,7 +484,7 @@ class ErrorCard extends StatelessWidget {
break;
case ErrorActionType.signIn:
// Navigate to sign in page
Navigator.of(context).pushReplacementNamed('/login');
NavigationService.navigateToServerConnection();
break;
case ErrorActionType.openSettings:
// Open app settings - would need platform-specific implementation