Home > Back-end >  "type 'Null' is not a subtype of type 'Iterable<dynamic>'"
"type 'Null' is not a subtype of type 'Iterable<dynamic>'"

Time:01-01

I'm trying to get the JSON response from the server and send it to the console but it's returning the following error.

enter image description here

Class BannerApi

class BannerApi {
  String id;
  String nome;
  String bclass;
  List<BannerItemApi>? bannerItem;

  BannerApi({
    required this.id,
    required this.nome,
    required this.bclass,
    required this.bannerItem,
  });

  factory BannerApi.fromJson(Map<String, dynamic> json) {
    inspect(json);
    return BannerApi(
      id: json['id'].toString(),
      nome: json['name'],
      bclass: json['class'],
      bannerItem: json['activeBannerItems'].length == 0
          ? null
          : List<BannerItemApi>.from(json['activeBannerItems'].forEach((x) {
              BannerItemApi.fromJson(x);
            })),
    );
  }
}

Class BannerItemApi

class BannerItemApi {
  String id;
  String titulo;
  String descricao;
  String imageUrl;

  BannerItemApi({
    required this.id,
    required this.titulo,
    required this.descricao,
    required this.imageUrl,
  });

  factory BannerItemApi.fromJson(Map<String, dynamic> json) {
    inspect(json);
    return BannerItemApi(
      id: json['item'][0]['id'].toString(),
      titulo: json['item'][0]['title'],
      descricao: json['item'][0]['text'],
      imageUrl: json['item'][0]['image'],
    );
  }
}

Server response does not return null at any time.

Inspect from BannerItemApi.fromJson(x)

enter image description here

CodePudding user response:

bannerItem: json['activeBannerItems'].length == 0
          ? null:.. 

replace for

bannerItem: json['activeBannerItems'].length == 0
              ? [] ...

in bannerapi

CodePudding user response:

Change

json['activeBannerItems'].length == 0
          ? null
          : List<BannerItemApi>.from(json['activeBannerItems'].forEach((x) {
              BannerItemApi.fromJson(x);
            })),

to

json['activeBannerItems'] == null
          ? null
          : (json['activeBannerItems'] as List)
              .map((i) => BannerItemApi.fromJson(i))
              .toList(),
  • Related