Go Router — Routing in Flutter

Muhamad Duta Chandra
4 min readAug 13, 2023

--

Hai, My name is Muhamad Duta Chandra. I am Mobile Developer from Indonesia.

Welcome to the PackageOfTheDay, my journey to explore Flutter packages on pub.dev!

In this article i wan’t to share about my understanding of Go Router packages. I hope you like it.

I provide the full code below :

Go_Router_POTD

Install and Set Up Go Router

We need to install and set up go router first.

Step 1: Add Dependency in pubspec.yaml

Open project’s pubspec.yaml file and add the GoRouter dependency under the dependencies section:

dependencies:
flutter:
sdk: flutter
go_router: ^10.0.0

make sure you install the version that work with your flutter sdk in GoRouter documentation pub.dev.

Step 2: Run flutter pub get

After adding the dependency, run the following command in your terminal to fetch and install the package:

flutter pub get

Step 3: Import the Required Packages

In your Dart file where you want to use GoRouter, import the necessary packages:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

Step 4: Define Route Names and Configurations

Create a class to define route names using constants. This will help ensure consistency and avoid typos in your route definitions.

abstract class PageName {
static const homeRoute = '/';
static const aboutRoute = '/about';
// ... define other routes
}

Step 5: Create Route Configuration

Configure the routes using the GoRoute and GoRouter classes. This includes specifying the initial route and nested routes.

final router = GoRouter(initialLocation: PageName.homeRoute, routes: [
GoRoute(
path: PageName.homeRoute,
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: PageName.aboutRoute,
builder: (context, state) => const AboutPage(),
),
// ... add other routes
],
),
]);

Step 6: Integrate into MaterialApp

In your main.dart or wherever you define your MaterialApp, assign the router configuration to the routerConfig property of MaterialApp.router:

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
routerConfig: router, // Assign the router configuration here
);
}
}

How to routing with Go Router?

Now we going to use go router for navigate from current page to the other page. There are several method to do the navigation, each method have it’s purpose and functionality.

Push Method

The Push Method is a common navigation approach that adds a new layer on top of the current screen. This allows users to easily navigate to a new page and then return to the previous screen using the back button.

ElevatedButton(
onPressed: () {
context.push(PageName.aboutRoute); // Navigate to the about page
},
child: const Text('Go to the about page'),
),

Push Replacement Method

The Push Replacement Method is used when you want to replace the current screen with a new one. This can be useful when navigating from a login or splash screen to the main app screen, ensuring the replaced screen won’t appear in the back stack.

ElevatedButton(
onPressed: () {
context.pushReplacement(PageName.aboutRoute); // Replace current screen with about page
},
child: const Text('Go to the about page'),
),

Go Method

The Go Method is similar to the Push Replacement Method, as it also replaces the current screen. It provides an alternative way to achieve the same effect.

ElevatedButton(
onPressed: () {
context.go(PageName.aboutRoute); // Go to the about page (replace current screen)
},
child: const Text('Go to the about page'),
),

Passing Single Argument

In addition to navigating between screens, Go Router supports passing arguments to different pages. The following example demonstrates how to pass a single argument to a page.

ElevatedButton(
onPressed: () {
GoRouter.of(context).push(
PageName.argumentsRoute,
extra: 'Argument from homepage',
);
},
child: const Text('Go to the arguments page'),
),

In the app_route we need to add extra to the widget constructor so we can use it

// With Single Argument
GoRoute(
path: PageName.arguments,
builder: (context, state) => ArgumentsPage(extra: state.extra as String?)
),

Add the constructor in the page so we can display it later

class ArgumentsPage extends StatelessWidget {
final String? extra; // Declare the argument variable

const ArgumentsPage({
Key? key,
this.extra,
}) : super(key: key);

...

// Display the argument
Text(extra!, style: const TextStyle(fontSize: 16,fontWeight: FontWeight.w800)
),

Passing Multiple Arguments

For more complex scenarios, you might need to pass multiple arguments to a page. Go Router makes this process straightforward as well.

ElevatedButton(
onPressed: () {
GoRouter.of(context).push(
PageName.multiArgumentsRoute,
extra: {
'arg1': 'First argument from homepage',
'arg2': 'Second argument from homepage',
},
);
},
child: const Text('Go to the multi-arguments page'),
),

In the app_route we need to add extra to the widget constructor so we can use it

// With Multiple Arguments
GoRoute(
path: PageName.multiArguments,
builder: (context, state) => MultiArgumentsPage(extra: state.extra as Map<String, dynamic>?)
),

Add the constructor in the page so we can display it later

class MultiArgumentsPageextends StatelessWidget {
final Map<String, dynamic>? extra; // Declare the argument variable

const MultiArgumentsPage({
Key? key,
this.extra,
}) : super(key: key);

...

// Display the argument
Column(children: [
Text(extra!['arg1'], style: const TextStyle(fontSize: 16,fontWeight: FontWeight.w800)),
Text(extra!['arg2'], style: const TextStyle(fontSize: 16,fontWeight: FontWeight.w800)),
]

Conclusion

Go Router is one of the best and effective way to routing in flutter, understanding the different navigation methods and argument passing techniques can greatly enhance your Flutter app’s development. By utilizing the Push, Push Replacement, and Go methods, as well as passing single and multiple arguments, you can seamlessly navigate between screens and share relevant data across your app’s components. Incorporate these methods into your app’s navigation strategy to create a smooth and engaging user journey.

This is the end for the #PackageOfTheDay.

Thank You.

--

--

Muhamad Duta Chandra

I am flutter developer with amazing skills, attention to detail, and dedication to creating exceptional user experiences to the app i build