I am trying to send map data from one page to other using routes in Flutter . and getting this Error

Issue

Sending Code

 Navigator.pushReplacementNamed(context, '/home',arguments: {
      "main_value":main,
      "desc_value":description,
      "temp_value":temp,
      "humidity_value":humidity,
    });

Receiving Code

Widget build(BuildContext context) {
    Map  info = *ModalRoute.of(context).settings.arguments;*
    return Scaffold(
        appBar: AppBar(
          title: const Text("HOME"),
        ),

This line getting an error

Map info = ModalRoute.of(context).settings.arguments;

A value of type ‘Object?’ can’t be assigned to a variable of type ‘Map<dynamic, dynamic>’.
Try changing the type of the variable, or casting the right-hand type to ‘Map<dynamic, dynamic>’.

Solution

ModalRoute.of(context).settings.arguments; returns a type of Object? that can’t be assigned directly to a Map, this is because arguments allow you to put any value in it, so you just need to cast it to the correct value

Widget build(BuildContext context) {
    Map info = ModalRoute.of(context).settings.arguments as Map;
    ...
}

it could also be useful to have a check before that, since arguments can contain anything!

you can use is for the check:

final arguments = ModalRoute.of(context).settings.arguments;
if(arguments is Map) {
   //YOUR LOGIC
} else {
   //YOUR ALTERNATIVE
}

Answered By – CLucera

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *