type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast

Viewed 7018

i have this error while i want to create dynamic navigation with multiple pages.. here is code below..

import 'package:flutter/material.dart';
import 'screens/locations/locations.dart';
import 'screens/location_detail.dart';

 const LocationsRoute = "/";
 const LocationDetailRout = '/location_detail';

 class App extends StatelessWidget {
   @override
   Widget build(BuildContext context) {
   return MaterialApp(
    onGenerateRoute: _routes(),
);

}

 RouteFactory _routes() {
   return (settings) {
   // final Map<String, dynamic> arguments = settings.arguments;
    final arguments = settings.arguments as Map<String, dynamic>;
    Widget screen;
    switch (settings.name) {
      case LocationsRoute:
      screen = Locations();
      break;
      case LocationDetailRout:
      screen = LocationDetail(arguments['id']);
  }
};

}

}

3 Answers

Quick fix

Map arguments = (settings.arguments??{}) as Map;

According to flutter official documentation at https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments The onGenerateRoute() function creates the correct route based on the given RouteSettings.

So the thing that we have been doing wrong was that we were looking for arguments for every route in the main block (outside of switch statements), but only LocationDetailRoute route has the arguments that's why we were getting null for all other routes.

RouteFactory _routes() {
    return (settings) {
      Widget screen;
      switch (settings.name) {
        case LocationsRoute:
          screen = Locations();
          break;
        case LocationDetailRoute:
          // Correct Place for this Statement
          final arguments = settings.arguments as Map<String, dynamic>; 
          screen = LocationDetails(arguments['id']);
          break;
        default:
          return null;
      }
      // return MaterialPageRoute(builder: (BuildContext context) => screen);
      return MaterialPageRoute(builder: (BuildContext context) => screen, settings: settings);
    };
  }

The arguments of RouteSettings can be Null and this is why you are seeing the error here final arguments = settings.arguments as Map<String, dynamic>; . You are basically trying to cast Null to a Map. Also i am not sure if this is intentional, but your inner function (the actual RouteFactory) is not returning a Route in any case.

Related