Here I have an enum defined as:
enum Routes<T, R> {
home(
name: '/home',
fromJson: HomeRouteArguments.fromJson,
navigate: navigateToHome,
),
const Routes({
required this.name,
required this.navigate,
this.fromJson,
this.additionalNames = const [],
});
final String name;
final List<String> additionalNames;
final T? Function(Map<dynamic, dynamic>)? fromJson;
final R? Function(BuildContext context, {required T args}) navigate;
}
Future<void> navigateToHome(BuildContext context,
{required HomeRouteArguments? args}) async {
//... stuff
}
HomeRouteArguments.fromJson
is just a named constructor of the HomeRouteArguments class.
I intend for the route arguments to always be supplied but optionally null. So for example:
Routes.home.navigate(context, args: null);
Because the named constructor returns a non-nullable type, it then sets the generic to that non-nullable type. So when I use the method it requires args
to be a non-null value. When I don’t supply the fromJson parameter however it works just as I intend.
Help would be appreciated.
Making the return type of the fromJson nullable doesn’t seem to fix it (as I have put in this example). Currently the
only thing I can do is remove the return type from the fromJson parameter but I would rather have the type there for safety.
Setting the generic values when initializing the values doesn’t work either.