Skip to content

Navigation

Dustin Catap edited this page Jun 19, 2024 · 2 revisions

The project uses auto_route as the navigation solution. It is based on Flutter's Navigator 2.0 and provides the following feature:

  • Declarative routing
  • Route guards
  • Nested navigation
  • Similar API compared to Flutter's Navigator 1.0, including as passing argument and result

See NavigationService and RootAutoRouter classes for more details.

Push Navigation

final isUserVerified = await _navigationService.push<bool>(const UserVerificationViewRoute());

Passing Parameter

For example, you want to pass userId to UserVerificationView.

Updating a route to receive parameter

Add the parameter userId to the constructor of the view.

@RoutePage()
class UserVerificationView extends StatelessWidget {
  const UserVerificationView({String? userId}) : super(key: const Key(UserVerificationViewRoute.name));
}

Run build_runner and UserVerificationViewRoute will have an optional parameter named userId. It will generate as well UserVerificationViewRouteArgs class that will be used to pass the parameter.

Updating the view model to receive the parameter

Implement Initializable interface in your view model and provide the type of the parameter you want to receive. In this case, since we are navigating to UserVerificationView, we will implement Initializable<UserVerificationViewRouteArgs>.

@injectable
class UserVerificationViewModel implements Initializable<UserVerificationViewRouteArgs> {
  String? userId;

  @override
  Future<void> onInitialize(UserVerificationViewRouteArgs? args) async {
    userId = args?.userId;
  }
}

Passing the parameter

You can pass the parameter when navigating to the route.

final isUserVerified = await navigation.push<bool>(const UserVerificationViewRoute(userId: 'asda-123-asd'));

Pop Navigation

Pop current route and return true to previous route.

await _navigationService.pop(true);

💡 IMPORTANT

  • When passing a parameter, be sure that you are passing the correct type, or else you will encounter TypeError during runtime when navigating.
  • When adding a parameter to the view, be sure that it should either be nullable or have a default value.

Route Guards

Route guards are used to prevent navigation to a route based on certain conditions. To implement route guards using the auto_route package, read it here.