Home > Software engineering >  What is wrong with this statement? type 'List<dynamic>' is not a subtype of type �
What is wrong with this statement? type 'List<dynamic>' is not a subtype of type �

Time:04-07

    List<NotificationSettingEntity> notificationList =
        json['notificationList'] ??
            []
                .map<NotificationSettingEntity>(
                    (ntJson) => NotificationSetting.fromJson(ntJson))
                .toList();

I've checked json['notificationList'] is List through runTimeType. and I just want an empty array if null. Shouldn't this be working? I've tried with [].

Thank you!

CodePudding user response:

Add () to json['notificationList'] ?? [].

Because json['notificationList'] is List<dynamic> and ?? only work when it null. So we add () to make .map alway call whatever json is null or not.

  List<NotificationSettingEntity> notificationList =
        (json['notificationList'] ?? [])
                .map<NotificationSettingEntity>((ntJson) => NotificationSetting.fromJson(ntJson))
                .toList();

CodePudding user response:

 List<NotificationSettingEntity> notificationList =
    (json['notificationList'] as List<dynamic>)
            .map<NotificationSettingEntity>(
                (ntJson) => NotificationSetting.fromJson(ntJson))
            .toList();

You should use 'as List' when you are fetching list from api

  • Related