The go_router
package is a declarative navigation system for Flutter. It supports deep linking and is compatible with mobile (iOS/Android) and web platforms.
feat: install go_route by thirdygayares · Pull Request #1 · thirdygayares/Flutter
1. Install go_router
Add go_router
to your project in pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
go_router: ^14.6.2
Run the following command to install it:
flutter pub get
-
Create Screens
import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home Page')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('Home Page'), ElevatedButton( onPressed: () { context.go('/login'); }, child: Text('Go to Login'), ), ], ), ), ); } }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class DashboardPage extends StatelessWidget { final String id; DashboardPage({required this.id}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Dashboard')), body: Center( child: Text('Dashboard Page for ID: $id'), ), ); } }
import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Login Page')), body: Center( child: ElevatedButton( onPressed: () { context.go('/dashboard/123'); }, child: Text('Go to Dashboard'), ), ), ); } }
3. Define Routes
Create router.dart in core directory
Example Code for Routing:
import 'package:go_router/go_router.dart';
import '../features/auth/screen/login_page.dart';
import '../features/dashboard/screen/dashboard_page.dart';
import '../features/homepage/screen/home_page.dart';
final GoRouter appRouter = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomePage(),
),
GoRoute(
path: '/login',
builder: (context, state) => LoginPage(),
),
GoRoute(
path: '/dashboard/:id',
builder: (context, state) {
final id = state.pathParameters['id'];
return DashboardPage(id: id!);
},
),
],
);
4. import 'core/route.dart';
import 'package:flutter/material.dart';
import 'core/route.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: appRouter,
title: 'Flutter GoRouter Example',
);
}
}
Feature | Usage |
---|---|
Declarative Routes | Define all routes centrally. |
Dynamic Parameters |
|
Programmatic Navigation | Use |
Web URL Handling | Supports deep linking for web. |
Back Navigation | Automatically supports "back" button handling. |
Output
-
/
→ DisplaysHomePage
. -
/login
→ Navigates toLoginPage
. -
/dashboard/123
→ DisplaysDashboardPage
with ID123
.