Flutter Navigation Patterns
GoRouter Setup
// lib/router.dart
final routerProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authProvider);
return GoRouter(
initialLocation: '/home',
redirect: (context, state) {
final isLoggedIn = authState == AuthState.authenticated;
final isAuthRoute = state.matchedLocation.startsWith('/auth');
if (!isLoggedIn && !isAuthRoute) return '/auth/login';
if (isLoggedIn && isAuthRoute) return '/home';
return null;
},
routes: [
GoRoute(path: '/auth/login', builder: (_, __) => const LoginPage()),
ShellRoute(
builder: (context, state, child) => AppShell(child: child),
routes: [
GoRoute(
path: '/home',
builder: (_, __) => const HomePage(),
),
GoRoute(
path: '/profile/:userId',
builder: (_, state) => ProfilePage(userId: state.pathParameters['userId']!),
routes: [
GoRoute(
path: 'edit',
builder: (_, state) => EditProfilePage(userId: state.pathParameters['userId']!),
),
],
),
],
),
],
);
});
Programmatic Navigation
// Push (stack)
context.push('/profile/123');
// Replace current route
context.replace('/home');
// Go (clear stack to route)
context.go('/home');
// Pop
context.pop();
// Pop with result
context.pop({'saved': true});
// Push and await result
final result = await context.push<Map<String, dynamic>>('/settings');
if (result?['saved'] == true) { ... }
Route Parameters
GoRoute(
path: '/product/:id',
builder: (context, state) {
final id = state.pathParameters['id']!; // /product/42
final tab = state.uri.queryParameters['tab'] ?? 'info'; // ?tab=reviews
final extra = state.extra as Product?; // passed via context.push extra
return ProductPage(id: id, tab: tab, product: extra);
},
),
// Navigate with extra data (not URL-serialized)
context.push('/product/42', extra: product);
ShellRoute for Persistent Bottom Nav
ShellRoute(
builder: (context, state, child) {
return Scaffold(
body: child,
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex(state.uri.toString()),
onTap: (i) => context.go(_tabs[i]),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
),
);
},
routes: [
GoRoute(path: '/home', builder: ...),
GoRoute(path: '/search', builder: ...),
GoRoute(path: '/profile', builder: ...),
],
),
Deep Linking Configuration
# android/app/src/main/AndroidManifest.xml intent-filter
# Add inside <activity>:
# <intent-filter android:autoVerify="true">
# <action android:name="android.intent.action.VIEW" />
# <category android:name="android.intent.category.DEFAULT" />
# <category android:name="android.intent.category.BROWSABLE" />
# <data android:scheme="https" android:host="myapp.example.com" />
# </intent-filter>
// GoRouter handles deep links automatically when paths match
GoRouter(
routes: [
GoRoute(path: '/share/:code', builder: (_, state) =>
SharePage(code: state.pathParameters['code']!)),
],
);
// https://myapp.example.com/share/ABC123 → SharePage(code: 'ABC123')
Nested Navigation (per-tab history)
// Use StatefulShellRoute for independent navigation stacks per tab
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return ScaffoldWithNavBar(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(routes: [GoRoute(path: '/home', builder: ...)]),
StatefulShellBranch(routes: [GoRoute(path: '/search', builder: ...)]),
],
),
Error and Loading Routes
GoRouter(
errorBuilder: (context, state) => ErrorPage(error: state.error),
routes: [...],
);
Testing Routes
testWidgets('navigates to profile', (tester) async {
final router = GoRouter(routes: appRoutes);
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
router.push('/profile/1');
await tester.pumpAndSettle();
expect(find.byType(ProfilePage), findsOneWidget);
});