Flutter
Coding and Programming
07
1 GoRouter
The GoRouter package is a powerful and
flexible navigation solution for Flutter,
providing easy handling of declarative
routing, URL-based navigation, and deep
linking. Here’s a quick guide to get started
with GoRouter in Flutter.
Step 1: Add GoRouter to Your Project
Add go_router to your pubspec.yaml file
dependencies: go_router: ^7.0.0 # Check
for the latest version
Run flutter pub get to install the package.
1-2 GoRouter Example
void main() {
runApp(const MyApp()); final GoRouter goRouterConfig = GoRouter(
} initialLocation: '/home',
routes: [
class MyApp extends StatelessWidget { GoRoute(
const MyApp({super.key}); name: "/home",
path: "/home",
@override builder: (context, state) {
Widget build(BuildContext context) { return const HomePage();
return MaterialApp.router( },
title: 'Flutter Demo', ),
debugShowCheckedModeBanner:
false, ],
routerConfig: goRouterConfig, );
);
}
}
1-3 Navigating Between Pages
With GoRouter, you navigate using the
GoRouter instance. Here's how to navigate
to different routes.
context.go('/details') replaces the
current route with /details.
context.push('/details') adds /details
on top of the current route.
context.pop() Use to go back to the
previous screen in a typical Navigator
stack.
1-4 Passing Parameters
To pass parameters to routes, define the path with
placeholders (:paramName), and use state.params to
retrieve them.
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/details/:id',
builder: (context, state) {
final id = state.pathParameters['id'];
return DetailScreen(id: id!);
},),
],);
// Navigating with a parameter
context.go('/details/123');
Thanks
Do you have any
questions?
!
Resources
https://flutter.dev