redirect property

GoRouterRedirect? redirect
final

An optional redirect function for this route.

In the case that you like to make a redirection decision for a specific route (or sub-route), consider doing so by passing a redirect function to the GoRoute constructor.

For example:

final GoRouter _router = GoRouter(
  routes: <GoRoute>[
    GoRoute(
      path: '/',
      redirect: (_) => '/family/${Families.data[0].id}',
    ),
    GoRoute(
      path: '/family/:fid',
      pageBuilder: (BuildContext context, GoRouterState state) => ...,
    ),
  ],
);

If there are multiple redirects in the matched routes, the parent route's redirect takes priority over sub-route's.

For example:

final GoRouter _router = GoRouter(
  routes: <GoRoute>[
    GoRoute(
      path: '/',
      redirect: (_) => '/page1', // this takes priority over the sub-route.
      routes: <GoRoute>[
        GoRoute(
          path: 'child',
          redirect: (_) => '/page2',
        ),
      ],
    ),
  ],
);

The context.go('/child') will be redirected to /page1 instead of /page2.

Redirect can also be used for conditionally preventing users from visiting routes, also known as route guards. One canonical example is user authentication. See Redirection for a complete runnable example.

If BuildContext.dependOnInheritedWidgetOfExactType is used during the redirection (which is how of method is usually implemented), a re-evaluation will be triggered if the InheritedWidget changes.

Implementation

final GoRouterRedirect? redirect;