Error consuming data from an API - void' is not a subtype of type '(dynamic)

Viewed 41

I'm consuming an api to register information in the database. Registration is always successful, but I get this error:

_TypeError (type '(String, dynamic) => void' is not a subtype of type '(dynamic) => dynamic' of 'f')

UPDATE

the error occurs in that specific block:

 Model.fromJson(Map<String, dynamic> json) {
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((String key, dynamic v) => data!.add(Data(
            value: v,
       )));
    });
 }
.
.
.

My date definition is this:

class Data {
  String? id;
  String? type;
  User? user;
  String? value;
  String? status;
  // List<Null>? errors;
  String? createdAt;
  // Null? verificationCode;
  // Null? crossValidationIdentifier;

  Data({
    this.id,
    this.type,
    this.user,
    this.value,
    this.status,
    this.createdAt,
  });

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    type = json['type'];
    user = json['user'] != null ? new User.fromJson(json['user']) : null;
    value = json['value'];
    status = json['status'];

    createdAt = json['createdAt'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['type'] = this.type;
    if (this.user != null) {
      data['user'] = this.user!.toJson();
    }
    data['value'] = this.value;
    data['status'] = this.status;

    data['createdAt'] = this.createdAt;

    return data;
  }
}

Finally, this is the method of including the record along with the return (status 200) of what I get:

 try {
      data: jsonEncode(queryParameters),
      options: Options(
              headers: headerParameters,
              contentType: 'application/json',
              responseType: ResponseType.json));
      
     if (response.statusCode == 200) {
        var saida = Model.fromJson(response.data); //the image refers to this line
        return saida;
      }
    } on DioError catch (exc) {
      throw ('Exception ${exc.message}');
    }
    return null;
  }

enter image description here

I appreciate if someone helps me analyze!

1 Answers

The problem is with the anonymous function you pass as the argument to forEach. The type of json['data'] is a map. If you call forEach on a map, you need to provide a function with two arguments: key and value. You function has one argument.

Related