Home > Blockchain >  Dart: The argument type Iterable<dynamic>? can't be assigned to the parameter type Iterab
Dart: The argument type Iterable<dynamic>? can't be assigned to the parameter type Iterab

Time:08-06

The class below is a stripped-down version of code generated at https://app.quicktype.io/ There are two lines like this:

genreIds: json["genre_ids"] == null ? null : List<int>.from(json["genre_ids"].map((x) => x)),

The initial error is The method can't be unconditionally invoked because the receiver can't be 'null'. That can be fixed by making the call conditional: ?.map .Making that change results in this error: 'The argument type Iterable<dynamic>? can't be assigned to the parameter type Iterable<dynamic>'. I can't see how to fix the second error.

class MovieResult {
    MovieResult({
        this.genreIds,
    });
    final List<int>? genreIds;
    factory MovieResult.fromRawJson(String str) => MovieResult.fromJson(json.decode(str));
    String toRawJson() => json.encode(toJson());
    factory MovieResult.fromJson(Map<String, dynamic> json) => MovieResult(
        genreIds: json["genre_ids"] == null ? null : List<int>.from(json["genre_ids"].map((x) => x)),
    );
    Map<String, dynamic> toJson() => {
        "genre_ids": genreIds == null ? null : List<dynamic>.from(genreIds.map((x) => x)),// *****ERROR*****
    };
}

CodePudding user response:

Use ! while you've already checked null

List<dynamic>.from(genreIds!.map((x) => x)),  

CodePudding user response:

Your genreIds can be null so the List returned in that case may also be null. Fix this by changing

List<dynamic> to List<dynamic>?

So toJson() method will become

Map<String, dynamic> toJson() => {
        "genre_ids": genreIds == null ? null : List<dynamic>?.from(genreIds.map((x) => x)),
    };
  • Related