'Object?' 类型的值 不能分配给类型为“Map<dynamic, dynamic>”的变量。它是一个路由错误

Moh*_*Ali 1 flutter

错误是当我尝试使用 ModalRoute.of(context).settings.arguments 时出现错误。我也想将它保存在地图中,但不能。

Map data = {};
data = ModalRoute.of(context).settings.arguments; // this is the error;
Run Code Online (Sandbox Code Playgroud)

错误:“对象?”类型的值 不能分配给类型为“Map<dynamic, dynamic>”的变量。

  • “对象”来自“dart:core”。
  • “地图”来自“飞镖:核心”。数据 = ModalRoute.of(context).settings.arguments;

小智 14

尝试使用:

data=ModalRoute.of(context)?.settings?.arguments as Map;
Run Code Online (Sandbox Code Playgroud)

?用于空安全


Saw*_*aha 11

经过这么多问题,最后,解决方案出奇的简单。

Map data = {};
data = ModalRoute.of(context).settings.arguments as Map; 
Run Code Online (Sandbox Code Playgroud)


Gou*_*har 2

您可以使用以下代码来做到这一点:

Map <String, Object>data = {}; // as the arguments passed from 
data = {"dataKey":ModalRoute.of(context).settings.arguments};
Run Code Online (Sandbox Code Playgroud)

然后,通过调用访问你的参数

data["dataKey"] // it will return the arguments