Skip to content

Latest commit

 

History

History
201 lines (156 loc) · 3.97 KB

File metadata and controls

201 lines (156 loc) · 3.97 KB

Flutter Go Router

This guide explains routing in Flutter using the go_router package, including route types, navigation methods, error handling, and data passing.


📌 What is a Router in Flutter?

In Flutter, a router controls navigation between screens (pages) in an app.
It decides which widget to display when the user goes to a certain path (URL-like format, e.g. /profile).

go_router simplifies Flutter navigation by:

  • Supporting declarative routes
  • Handling deep links and web URLs
  • Making nested navigation easier
  • Adding query parameters and data passing support

1️⃣ Installation

  • Add the package to your pubspec.yaml:
dependencies:
  go_router: ^14.1.4

2️⃣ Creating the Router Class

  • Create a RouterClass to define all routes:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'home_page.dart';
import 'profile_page.dart';

class RouterClass {
  final router = GoRouter(
    initialLocation: "/",
    errorBuilder: (context, state) => Scaffold(
      body: Center(child: Text("404 - Page not found")),
    ),
    routes: [
      GoRoute(
        path: "/",
        builder: (context, state) => HomePage(),
      ),
      GoRoute(
        path: "/profile",
        builder: (context, state) => ProfilePage(),
      ),
    ],
  );
}

3️⃣ Adding Routes

GoRoute(
  path: "/about",
  builder: (context, state) => AboutPage(),
),

4️⃣ Integrating Navigator

  • In main.dart:
import 'package:flutter/material.dart';
import 'router_class.dart';

void main() {
  final routerClass = RouterClass();
  runApp(MyApp(router: routerClass.router));
}

class MyApp extends StatelessWidget {
  final GoRouter router;
  const MyApp({super.key, required this.router});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
    );
  }
}

5️⃣ Navigating to Pages

ElevatedButton(
  onPressed: () => GoRouter.of(context).go('/profile'),
  child: Text("Go to Profile"),
)

6️⃣ Error Handling

  • Handled via errorBuilder in GoRouter:
errorBuilder: (context, state) => Scaffold(
  body: Center(child: Text("404 - Page not found")),
),

7️⃣ Nested Routes

GoRoute(
  path: "/profile",
  builder: (context, state) => ProfilePage(),
  routes: [
    GoRoute(
      path: "settings",
      builder: (context, state) => SettingsPage(),
    ),
  ],
),

8️⃣ Passing Data

  • Path Parameters:
GoRoute(
  path: "/user/:id",
  builder: (context, state) {
    final id = state.pathParameters['id']!;
    return UserPage(userId: id);
  },
);

Navigate:
GoRouter.of(context).go('/user/123');

9️⃣ Named Routes

GoRoute(
  name: 'profile',
  path: "/profile",
  builder: (context, state) => ProfilePage(),
),

Navigate:
GoRouter.of(context).goNamed('profile');

🔟 Query Parameters

GoRoute(
  path: "/age",
  builder: (context, state) {
    final age = int.parse(state.uri.queryParameters['age'] ?? '0');
    return AgePage(age: age);
  },
);

Navigate:
GoRouter.of(context).go('/age?age=25');

1️⃣1️⃣ Redirects

redirect: (context, state) {
  final loggedIn = false;
  if (!loggedIn) return '/login';
  return null;
},

1️⃣2️⃣ Push and PushNamed

// Push to a new page (keeps current page in stack)
GoRouter.of(context).push('/profile');

// Push named route
GoRouter.of(context).pushNamed('profile');

✅ Summary

  • go_router makes Flutter navigation:
  • Easier to manage
  • Web-friendly (deep links)
  • Scalable for complex apps
  • Use path parameters, query parameters, and nested routes for dynamic navigation in your Flutter apps.