Push and Pop Navigation
// Navigate to a new screen:
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const DetailsPage(id: 42)),
);
// Navigate back:
Navigator.pop(context);
// Navigate and return a result:
final result = await Navigator.push<String>(
context,
MaterialPageRoute(builder: (_) => const InputPage()),
);
print('Got: $result'); // from InputPage: Navigator.pop(context, 'hello')
// Replace current screen (no back button):
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const HomePage()),
);
// Go all the way back to first screen:
Navigator.popUntil(context, ModalRoute.withName('/'));
Named Routes
MaterialApp(
initialRoute: '/',
routes: {
'/': (ctx) => const HomePage(),
'/details': (ctx) => const DetailsPage(),
'/settings': (ctx) => const SettingsPage(),
'/login': (ctx) => const LoginPage(),
},
)
// Navigate:
Navigator.pushNamed(context, '/details');
Navigator.pushNamed(context, '/details', arguments: {'id': 42});
GoRouter Package
go_router is Google's recommended solution for declarative, deep-linkable navigation:
import 'package:go_router/go_router.dart';
final router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(path: '/', builder: (_, __) => const HomePage()),
GoRoute(
path: '/users/:id',
builder: (ctx, state) {
final id = state.pathParameters['id']!;
return UserPage(userId: id);
},
),
GoRoute(path: '/settings', builder: (_, __) => const SettingsPage()),
],
);
// Usage: context.go('/users/42');
// context.push('/settings');
// context.pop();
Passing Data Between Screens
// Option 1: Constructor parameters (simplest)
Navigator.push(context,
MaterialPageRoute(builder: (_) => ProductPage(product: selectedProduct)));
// Option 2: Route arguments
Navigator.pushNamed(context, '/product', arguments: selectedProduct);
// In ProductPage:
final product = ModalRoute.of(context)!.settings.arguments as Product;
// Option 3: GoRouter path parameters + query params
context.go('/products/42?view=detail');
🧠 Quiz
1. What does Navigator.pop(context, result) do?
- A) Navigates to the root
- B) Removes the current screen and optionally returns a value to the caller ✅
- C) Clears the navigation stack
- D) Pushes a new screen
2. Which navigation package is Google's recommended approach for declarative deep-linkable routing?
- A) flutter_navigation
- B) auto_route
- C) go_router ✅
- D) nav_2
Summary
Flutter navigation uses a stack: Navigator.push() adds screens, Navigator.pop() removes them. Named routes (routes map in MaterialApp) are simple for small apps. Use go_router for deep linking, URL-based routing, and complex navigation flows. Pass data via constructor arguments, route arguments, or path parameters.