I try to use some flutter example, but now flutter is very strict (null problem) so most flutter examples has to be modified. Most are easy (you need just add '?'). But i have no idea how to fix this:
class Navigation {
static Future<T?> navigateTo<T>({
required BuildContext context,
required Widget screen,
required NavigationRouteStyle style,
}) async {
Route? route;
if (style == NavigationRouteStyle.cupertino) {
route = CupertinoPageRoute<T>(builder: (_) => screen);
} else if (style == NavigationRouteStyle.material) {
route = MaterialPageRoute<T>(builder: (_) => screen);
}
return await Navigator.push<T>(context, route);
}
}
and line return await Navigator.push<T>(context, route)
causes error:
The argument type 'Route?' can't be assigned to the parameter type 'Route'.
CodePudding user response:
I'm not 100% sure what NavigationRouteStyle
is, since it doesn't appear in the flutter sdk, and you didn't provide a definition for it. I'm going to assume it is an enum with just cupertino
and material
like so:
enum NavigationRouteStyle {
cupertino,
material
}
What I would suggest is to change the type of route
from Route?
to Route<T>
, since Navigator.push
expects a Route<T>
. Secondly I would convert the if-else to a switch statement since switch statements can do exhaustivity checks on enums, which allows route
to be non-nullable so long as its assigned in all cases.
class Navigation {
static Future<T?> navigateTo<T>({
required BuildContext context,
required Widget screen,
required NavigationRouteStyle style,
}) async {
Route<T> route;
switch (style) {
case NavigationRouteStyle.cupertino:
route = CupertinoPageRoute<T>(builder: (_) => screen);
break;
case NavigationRouteStyle.material:
route = MaterialPageRoute<T>(builder: (_) => screen);
break;
}
return await Navigator.push<T>(context, route);
}
}