Search code examples
flutterdartdart-null-safety

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


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*****
    };
}

Solution

  • Use ! while you've already checked null

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