[flutter]How to use go_router

image

What is go_router?

In a nutshell, go_router is a convenient package for managing screen transitions.

It’s an upgrade over Navigator.

Features are as follows:

  • Parsing paths and query parameters using template syntax (e.g., “user/:id”).
  • Support for displaying multiple destination (sub-route) screens and performing redirects.
  • Support for redirecting users to different URLs based on the application’s state, like signing in when a user is not authenticated.
  • Support for multiple Navigators using ShellRoute – You can display an inner Navigator that shows custom pages based on matched routes. For example, to display a BottomNavigationBar shown at the bottom of the screen, you can use this approach.
  • Supports both Material and Cupertino apps.
  • Backward compatibility with the Navigator API.

For more details, please refer to the official documentation.

Basic Usage

Let’s start by looking at the basic usage.

Designing Screen Transitions

First, design the screen transitions.

For example, something like this:

You’ll describe the screens you want to transition to one by one like this:

Where:

  • desired/path: Specify the path, similar to a directory structure (use ‘/’ for the screen you want to show first when the app launches).

Preparing to use go_router

To implement screen transitions using go_router, you need to define MaterialApp.router as shown in the following code:

Creating Screens

Create the screens you want to transition to.

The Initial Screen

Transitioning from the Initial Page

Executing the App

How to Perform Screen Transitions

When you want to transition screens, write code like this:

Three Ways to Transition Screens

  • go('destination/path'): Replace the current screen with the destination screen.
  • push('destination/path'): Stack the destination screen on top of the currently displayed screen.
  • pop(): Go back to the previous stack.

For more details, refer to the API reference.

Using bottomNavigationBar

Designing Screen Transitions with BottomNavigationBar

When using BottomNavigationBar, use ShellRouter().

Implementing Each Page

The Initial Page

Note: Using context.push('page1') will display the pure Page1.dart (without showing the BottomNavigationBar), so be cautious.

Implementing BottomNavigationBar

For the body’s content, receive it through the argument passed by ShellRoute.

Implementing Page 1

Implementing Page 1 Detail

Implementation for Page 2 and Page 2 Detail is similar to Page 1, so it’s omitted.

App’s Execution Result

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


error: Content is protected !!