I'm currently evaluation switching from go_router to auto_route but I'm struggling with

Is it possible to define pages with required parameters with auto_route? Something like this:

@RoutePage()
class ProfilePage extends StatelessWidget {
  final Function() loadData;

  const ProfilePage({
    Key? key,
    required this.loadData
  }) : super(key: key);
}

When I configure this route like this:

AutoRoute(
  path: '/profile',
  page: ProfileRoute.page,
),

I can't specify the loadDate parameter.

On web, when I navigate to the /profile path and reload the page, I get the error ProfileRouteArgs can not be null because the corresponding page has a required parameter. The same error occurs when making the route as an initial route.

How would I deal with this? Is there any option besides making the parameters of my page optional and setting a default value?

1

There are 1 best solutions below

2
Vladyslav Ulianytskyi On

In your class ProfilePage function loadData is required. This is main reason why you got an error:

ProfileRouteArgs can not be null because the corresponding page has a required parameter.

It is not really about auto_rote. If the parameter of your page is a function and you want to set default value to this param, you could do this:

@RoutePage()
class ProfilePage extends StatelessWidget {
  const ProfilePage({
    this.loadData = _getDefaultFunc,
    super.key,
  }) : super(key: key);

  final Function() loadData;

  static Function() _getDefaultFunc() {
     return (){ ... do something...};
  }
}

And of course it could be easily done for other parameter types. More info: @autoroutePassingArguments

If you want to use required parameters, then:

AutoRouter.of(context).push(
      ProfilePage(
          loadData: (){
             ...do smthng...
          },
      ),
    );