我正在尝试使用 Flutter 中的路线将地图数据从一个页面发送到其他页面。并得到这个错误

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

发送代码

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

接收码

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

这行出错

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>'.

像这样投射 arguments 到地图:

Map<String, dynamic> info = ModalRoute.of(context).settings.arguments as Map<String, dynamic >;

改变这个:

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

对此:

final info = ModalRoute.of(context).settings.arguments as Map<String,String>;

或者,如果您不知道值,请使用 Map<String,dynamic>

ModalRoute.of(context).settings.arguments; returns一种不能直接赋值给Map的Object?类型,这是因为arguments允许你在里面放任意值, 所以你只需要将它转换为正确的值

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

在此之前进行检查也很有用,因为 arguments 可以包含任何内容!

您可以使用 is 进行检查:

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