【问题标题】:The argument type 'List<Datum>?' can't be assigned to the parameter type 'List<Datum>'参数类型 \'List<Datum>?\' 不能分配给参数类型 \'List<Datum>\'
【发布时间】:2022-11-05 15:04:57
【问题描述】:

Flutter 环境:sdk: ">=2.17.0 <3.0.0"

错误:

I/flutter (28168): NoSuchMethodError: Class 'String' has no instance method 'map'.
I/flutter (28168): Receiver: ""
I/flutter (28168): Tried calling: map(Closure: (dynamic) => Datum)
E/flutter (28168): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'map'.
E/flutter (28168): Receiver: ""
E/flutter (28168): Tried calling: map(Closure: (dynamic) => Datum)

我尝试了以下解决方案

factory AddressGetResponse.fromJson(Map<String, dynamic> json) => AddressGetResponse(
    status: json["status"],
    message: json["message"],
    data: json["data"] == null ? null :List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
  );

但得到了上述错误:

参数类型“列表?”不能分配给参数类型“列表”。

【问题讨论】:

  • 你确定吗?你的 json['data'] 是 List 因为你的控制台提到它是 String 并且 String 没有方法映射。

标签: json flutter dart dart-null-safety


【解决方案1】:

您创建的模式AddressGetResponse,类似于List&lt;Datum&gt; data。表示数据不接受空值。

在空情况下,您正在做

data: json["data"] == null ? null :.....

意味着您正在尝试在不可为空的字段上分配空值。并且 null-safety 会引发错误。

您可以使数据字段为空`

class AddressGetResponse{
  final List<Datum>? data;
  .... 

或者在 null 情况下提供空列表。

 data: json["data"] == null ? []:List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),

更多关于understanding-null-safety

【讨论】:

    【解决方案2】:

    在你的模型中使用它

    data: json["data"]==null?[]:List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    

    【讨论】:

      【解决方案3】:

      找到了解决方案

      data: (json["data"] == null ? null :List&lt;Datum&gt;.from(json["data"].map((x) =&gt; Datum.fromJson(x))))!,

      敲击()中的数据并添加!给它。

      【讨论】:

        猜你喜欢
        • 2021-07-04
        • 2021-12-10
        • 2021-10-24
        • 2021-11-05
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 2020-05-28
        • 2021-11-06
        相关资源
        最近更新 更多