Home > Software engineering >  onGenerateRoute without IFs
onGenerateRoute without IFs

Time:11-18

I'm trying to implement this code without using ifs because of the quantity of routes that I need to put in it.

onGenerateRoute: (settings) {
    final args = settings.arguments as returnArguments;
    if (settings.name == "/avoid") {
      return MaterialPageRoute(
          builder: (context) => Avoid(
                info: args.info,
                url: args.url,
              ));
    }
    if (settings.name == "/doit") {
      return MaterialPageRoute(
          builder: (context) => Doit(
                info: args.info,
                url: args.url,
              ));
    }
    if (settings.name == "/trylater") {
      return MaterialPageRoute(
          builder: (context) => TryLater(
                info: args.info,
                url: args.url,
              ));

This code works fine the way that I want, this is the code I tried to resolve the problem but I keep getting error and I dont know why.

onGenerateRoute: (RouteSettings settings) {
            final args = settings.arguments as returnArguments;
  var routes = <String, WidgetBuilder>{
    "/avoid": (ctx) => Avoid(info: args.info, url: args.url),
     "doit" : (ctx) => Doit(info: args.info, url: args.url),     
    "/trylater": (ctx) => Trylater(info: args.info, url: args.url),
  };
  WidgetBuilder builder = routes[settings.name];
  return MaterialPageRoute(builder: (ctx) => builder(ctx));
}

this is the error I'm gettingenter image description here

CodePudding user response:

The error occurs because routes[settings.name] can be null e.g. if the key doesn't exists. To fix this you can either check if your value is not null

WidgetBuilder? builder = routes[settings.name];
if(builder != null){
  return MaterialPageRoute(builder: (ctx) => builder(ctx));
} else {
  // Handle null case
}

or you say that your variable is not null by using !, but then make sure it is not null.

WidgetBuilder builder = routes[settings.name]!;
  • Related