0
0
Fluttermobile~5 mins

GoRouter package in Flutter

Choose your learning style9 modes available
Introduction

GoRouter helps you move between screens in your Flutter app easily. It makes navigation simple and organized.

When you want to switch between different pages in your app.
When you need to pass information from one screen to another.
When you want to handle deep links or URLs in your app.
When you want to keep your navigation code clean and easy to manage.
Syntax
Flutter
final GoRouter router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => HomeScreen(),
    ),
    GoRoute(
      path: '/details',
      builder: (context, state) => DetailsScreen(),
    ),
  ],
);

GoRouter is created with a list of GoRoute objects.

Each GoRoute has a path and a builder that returns the screen widget.

Examples
This route shows the HomeScreen when the app starts.
Flutter
GoRoute(
  path: '/',
  builder: (context, state) => HomeScreen(),
)
This route passes a userId from the URL to the ProfileScreen.
Flutter
GoRoute(
  path: '/profile/:userId',
  builder: (context, state) {
    final userId = state.params['userId']!;
    return ProfileScreen(userId: userId);
  },
)
Sample App

This app starts on the Home screen with a button. When you tap the button, it navigates to the Details screen using GoRouter.

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

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

class MyApp extends StatelessWidget {
  final GoRouter _router = GoRouter(
    routes: [
      GoRoute(
        path: '/',
        builder: (context, state) => HomeScreen(),
      ),
      GoRoute(
        path: '/details',
        builder: (context, state) => DetailsScreen(),
      ),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
      title: 'GoRouter Demo',
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: ElevatedButton(
          onPressed: () => context.go('/details'),
          child: Text('Go to Details'),
        ),
      ),
    );
  }
}

class DetailsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Details')),
      body: Center(child: Text('Welcome to Details Screen!')),
    );
  }
}
OutputSuccess
Important Notes

Use context.go('/path') to navigate to a new screen.

Paths can include parameters like /profile/:id to pass data.

GoRouter works well with Flutter's MaterialApp.router for easy setup.

Summary

GoRouter makes screen navigation simple and clear.

Define routes with paths and screen builders.

Use context.go() to move between screens.