Home > Back-end >  The argument type 'List<Datum>?' can't be assigned to the parameter type '
The argument type 'List<Datum>?' can't be assigned to the parameter type '

Time:07-28

Flutter environment: sdk: ">=2.17.0 <3.0.0"

Error:

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)

I have tried the below solution

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

but got the above Error:

The argument type 'List?' can't be assigned to the parameter type 'List'.

CodePudding user response:

use this in your model

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

CodePudding user response:

The mode you created AddressGetResponse, it is something like List<Datum> data. Means data doesn't accept the null value.

On null cases, you are doing

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

Means you are trying to assign null value on non-nullable filed. And null—safety raise the error.

You can make the data filed nullable`

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

Or provide empty list on null case.

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

More about understanding-null-safety

  • Related