Simplifying Navigation in Flutter with GoRouter
5 min readMay 16, 2024
A Comprehensive Guide to Implementing GoRouter in Flutter Apps
Navigation in Flutter
“In Flutter, screens and pages are called routes.”
The Navigator class is a widget that manages a set of child widgets with a stack discipline, allowing for navigation between different screens in an app.
Navigator 2.0: GoRouter
To use GoRouter, we need to add it to a MaterialApp:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}
Next, create a class with a GoRouter constructor:
import 'package:go_router/go_router.dart';
// GoRouter configuration
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => SplashScreen(),
),
GoRoute(
path: '/home-screen',
builder: (context, state) => HomeScreen(),
),
],
);
Points to Note
- Replacing Navigator Methods: If you’re using
context.pushReplacementNamed
in the old route, replace it withcontext.go()
.
Usage:context.go('/home-screen');