Routing with go_router in Flutter
GoRouter is a navigation package for Flutter that provides a simple and flexible way to manage application navigation. It is based on the concept of named routes, which allows you to easily define and manage your app’s navigation paths using a simple and intuitive API.
Getting Started
To get started with GoRouter, you’ll need to add it as a dependency to your Flutter project by including it in your pubspec.yaml
file:
dependencies:
go_router: ^6.0.1
Once you’ve added GoRouter as a dependency, you can import it into your project and start using it.
Defining Routes
The first step in using GoRouter is to define your app’s routes. Routes in GoRouter are defined using the GoRoute
class, which takes a name, a path, and a widget builder as arguments.
Here’s an example of how you might define a couple of routes in your app:
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(routes: [
GoRoute(
path: "/",
name: '/',
builder: (context, state) => HomePage(),
),
GoRoute(
path: "/details/:id",
name: "details",
builder: (context, state) => DetailsPage(
id: state.params["id"].toString(),
),
)
]);
Lets use the router in our MyApp:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:go_route_example_app/router.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
routerConfig: router,
);
}
}
In this example, we’re defining two routes: a root route (/
) that displays the HomePage
widget, and a route that displays details about an item with a given ID (/details/:id
). Note that the :id
in the path is a parameter that can be accessed in the DetailsPage
widget using state.params['id']
.
Navigating
Once you’ve defined your app’s routes, you can use GoRouter to navigate between them. Navigating with GoRouter is as simple as calling the go
method on the GoRouterDelegate
object:
GoRouter.of(context).go('/details/123');
In this example, we’re navigating to the /details/123
route, which will display the DetailsPage
widget with an ID of 123
.
Navigation History
GoRouter also provides a simple way to navigate back and forward through the app’s navigation history. This is done using the back
and forward
methods on the GoRouterDelegate
object:
GoRouter.of(context).back();
GoRouter.of(context).forward();
Conclusion
In conclusion, GoRouter is a simple and flexible way to manage application navigation in Flutter. By defining named routes and using the GoRouterDelegate
to navigate between them, you can easily create a navigation system that is both intuitive and easy to use. With its simple API and built-in support for navigation history, GoRouter is a great choice for any Flutter project that requires flexible and reliable navigation.