Day 3 of 5

Navigation and Routing

Flutter's Navigator stack lets you push and pop routes. Today you will use Navigator.push for simple navigation, named routes for deep linking, and GoRouter for declarative URL-based routing.

bash
flutter pub add go_router
dart
// Imperative navigation
Navigator.push(context,
  MaterialPageRoute(builder: (_) => const DetailScreen(id: 1)));

// Pass data back
final result = await Navigator.push<String>(context,
  MaterialPageRoute(builder: (_) => const InputScreen()));
print(result); // value returned by Navigator.pop(context, 'done')
dart
// GoRouter — declarative routing
final router = GoRouter(
  routes: [
    GoRoute(path: '/', builder: (_, __) => const HomeScreen()),
    GoRoute(
      path: '/detail/:id',
      builder: (context, state) {
        final id = state.pathParameters['id']!;
        return DetailScreen(id: int.parse(id));
      },
    ),
  ],
);

// In main.dart
MaterialApp.router(routerConfig: router)

// Navigate anywhere
context.go('/detail/42');
context.push('/detail/42'); // adds to back stack

Exercise: Build a Multi-Screen App

  1. Set up GoRouter with Home / List / Detail routes
  2. Pass an item ID as a path parameter
  3. Read the param in DetailScreen and display data
  4. Add a BottomNavigationBar with 2 tabs
  5. Test the back button on Android and iOS

Day 3 Summary

Finished this lesson?