Bizarre behavior of Dart (in Flutter)

44 Views Asked by At

I have this code:

class Pack {
  Pack({
    required this.responseCode,
    required this.object,
  });

  int responseCode;
  dynamic object;

  factory Pack.fromJson(Map<String, dynamic> jsonString) => Pack(
        responseCode: jsonString['ResponseCode'],
        object: jsonString['Object'],
      );
}
class EntityTypeModel {
  EntityTypeModel({
    required this.entityTypeCode,
    required this.entityTypeName,
  });

  int entityTypeCode;
  String entityTypeName;

  factory EntityTypeModel.fromJson(Map<String, dynamic> jsonString) =>
      EntityTypeModel(
        entityTypeCode: jsonString['EntityTypeCode'],
        entityTypeName: jsonString['EntityTypeName'],
      );

  Map<String, dynamic> toJson() => {
        "EntityTypeCode": entityTypeCode,
        "EntityTypeName": entityTypeName,
      };
}
Future<dynamic> Test(String bodyString) async {
  Map<String, dynamic> bodyJson = json.decode(bodyString);

  final pack = Pack.fromJson(bodyJson);

  dynamic object= entityTypeListFromObject(pack.object);
  //...
}

and these two versions of code that, in theory, should do the exact same thing.

Version 1:

List<EntityTypeModel>? entityTypeListFromObject(dynamic object) {
  return object.map((element) => EntityTypeModel.fromJson(element)).toList();
}

Version 2:

List<EntityTypeModel>? entityTypeListFromObject(dynamic object) {
  if (object is List) {
    return object
        .map((element) => EntityTypeModel.fromJson(element))
        .toList();
  } else {
    throw Exception('Invalid response format');
  }
}

The input data "object" is ALWAYS a list not null and not empty. And the bodyString is:

{"ResponseCode":1,"Object":[{"EntityTypeCode":10,"EntityTypeName":""},{"EntityTypeCode":11,"EntityTypeName":""},{"EntityTypeCode":12,"EntityTypeName":""},{"EntityTypeCode":13,"EntityTypeName":""},{"EntityTypeCode":14,"EntityTypeName":""},{"EntityTypeCode":15,"EntityTypeName":""}]}

In Version 1, I obtains this error:

_TypeError (type 'List<dynamic>' is not a subtype of type 'List<EntityTypeModel>?')

WHY ???

1

There are 1 best solutions below

0
Josteve Adekanbi On

Try using List.from like so:

List<EntityTypeModel>? entityTypeListFromObject(dynamic object) {
  return List.from(object)
      .map((element) => EntityTypeModel.fromJson(element))
      .toList();
}