Navigation in Flutter using go_router

Osama Asif
2 min readDec 20, 2022

Are you going to implement Navigation 2.0? Use go_router 👍 This package uses a Router API to provide a convenient, URL-based API for navigating between different screens 🛰️.

Motivation

I used the go_router package in my flutter web application. And, this package helped me a lot. I implemented the parameter, nested, and dynamic routes, which were too easy to implement with the help of this package. There are some more things that I have achieved with go_router. But, we are good with the basics for a better understanding of this article.

So, Let’s start 🙌

STEP # 1

Import the go_router dependency in your flutter application👇

dependencies:
go_router: ^6.0.0

Take a look at the directory structure. 👇

STEP # 2

Now, jump into the app_routes file and declare our routes. 🤾🏼‍♂️.

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router_sample_app/screens/detail_screen.dart';
import 'package:go_router_sample_app/screens/home_screen.dart';

final GoRouter appRoutes = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) {
return const HomeScreen();
},
routes: <RouteBase>[
GoRoute(
path: 'details',
builder: (BuildContext context, GoRouterState state) {
return const DetailScreen();
},
),
],
),
],
);

We are using HomeScreen as a default or root route. Whenever we start the application user will automatically be redirected to the HomeScreen which is mapped with the ‘/’ and the DetailScreen route is mapped with ‘details’🙌

STEP # 3

import 'package:flutter/material.dart';
import 'package:go_router_sample_app/routes/app_routes.dart';

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

class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: appRoutes,
);
}
}

Now, instead of the material app use the MaterialApp.router for the router configuration ☝️

Great, now we are good with the configuration part 🥳

STEP # 4

   ElevatedButton(
onPressed: () => context.go('/details'),
child: const Text('Go to the Details screen'),
),

Use context.go(‘Any route name’) for navigating between screens.

DEMO

Hurray…!!!🥳🥳🥳

So these are the basic steps for implementing go_router in your flutter application. In the upcoming tutorial will also see the parameter routes using go_router. If you like it so, support me by giving claps and follow me to show some love😉

GitHub repo link ☝️

--

--

Osama Asif

Seasoned software engineer with over 6 years of extensive industry experience specializing in the development of mobile applications.