3

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 3

4

Quick fix

Map arguments = (settings.arguments??{}) as Map;
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    };
  }

Comments

0

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.

2 Comments

then how should i fixed it
You should probably only extract the arguments if you expect the route to have arguments. Or just check if arguments are Null before extracting (although this would crash further down when you try to access arguments)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.