English 中文(简体)
我获得名单<动力>不是“地图”的亚类。 类型。 问题:如何建立通用反应模式
原标题:I get List<dynamic> is not a subtype of type Map<String, dynamic>? in type cast. Question: How to Create generic response model

In some cases, the response.data can come as an object or a List example

{
    "status_code": 200,
    "status": "success",
    "data": [
        {
            "userID": "YSXrcA",
            "emailAddress": "[email protected]",
            "fullName": "John",
            "phoneNumber": "12345676556",
            "profilePic": "https://res.cloudinary.com/ddvype20r/image/upload/7/Group_720_wdae1i.png",
            "referralCode": "Ffit7q",
            "registerDate": "2023-12-06T20:25:37+01:00",
            "userType": "renter"
        }
    ]
}

<>>>>

{
    "status_code": 200,
    "status": "success",
    "data": 
        {
            "userID": "YSXrcA",
            "emailAddress": "[email protected]",
            "fullName": "John",
            "phoneNumber": "12345676556",
            "profilePic": "https://res.cloudinary.com/ddvype20r/image/upload/7/Group_720_wdae1i.png",
            "referralCode": "Ffit7q",
            "registerDate": "2023-12-06T20:25:37+01:00",
            "userType": "renter"
        }
    
}

我有一个反应模式,像这个模式类别一样。

class ApiResponseModel {
  final int status_code;
  final String? status;
  final String? message;
  final Map<String, dynamic>? data;
 

  ApiResponseModel({
    required this.status_code,
    required this.status,
    required this.message,
    this.data,
  });

  factory ApiResponseModel.fromJson(Map<String, dynamic> json, ) =>
      ApiResponseModel(
        status_code: json["status_code"],
        status: json["status"],
        message: json["message"],
     data: json[ data ] as Map<String, dynamic>?,
      );


  Map<String, dynamic> toJson() => {
        "status_code": status_code,
        "status": status,
        "message": message,
        "data": data!,
      };
}

然后可以发出呼吁

 Future<ApiResponseModel> login({required Map payload}) async {
    try {
      final result = await apiService.postRequest(
        endpoint:  /user/auth/login ,
        data: payload,
      );

      return ApiResponseModel.fromJson(result);
    } catch (err) {
      logger.log("Login Error: $err");
      rethrow;
    }
  }

this works fine if the response is the second from the responses above, but when it a list i get the error error rrr: type List is not a subtype of type Map<String, dynamic>? in type cast

问题回答

我为案件1设定了额外的模型。

class ApiResponseModel {
  final int status_code;
  final String? status;
  final String? message;
  final List<ApiResponseDataModel> data;
  ApiResponseModel({
    required this.status_code,
    this.status,
    this.message,
    required this.data,
  });

  ApiResponseModel copyWith({
    int? status_code,
    String? status,
    String? message,
    List<ApiResponseDataModel>? data,
  }) {
    return ApiResponseModel(
      status_code: status_code ?? this.status_code,
      status: status ?? this.status,
      message: message ?? this.message,
      data: data ?? this.data,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
       status_code : status_code,
       status : status,
       message : message,
       data : data.map((x) => x.toMap()).toList(),
    };
  }

  factory ApiResponseModel.fromMap(Map<String, dynamic> map) {
    return ApiResponseModel(
      status_code: map[ status_code ] as int,
      status: map[ status ] != null ? map[ status ].toString() : null,
      message: map[ message ] != null ? map[ message ].toString() : null,
      data: List<ApiResponseDataModel>.from(
        (map[ data ] as List).map<ApiResponseDataModel>(
          (x) => ApiResponseDataModel.fromMap(
              x as Map<String, dynamic>), // look what i did here
        ),
      ),
    );
  }

  String toJson() => json.encode(toMap());

  factory ApiResponseModel.fromJson(dynamic source) =>
      ApiResponseModel.fromMap(source as Map<String, dynamic>);
}

class ApiResponseDataModel {
  final String userID;
  final String emailAddress;
  final String fullName;
  final String profilePic;
  final String referralCode;
  final String registerDate;
  final String userType;
  ApiResponseDataModel({
    required this.userID,
    required this.emailAddress,
    required this.fullName,
    required this.profilePic,
    required this.referralCode,
    required this.registerDate,
    required this.userType,
  });

  ApiResponseDataModel copyWith({
    String? userID,
    String? emailAddress,
    String? fullName,
    String? profilePic,
    String? referralCode,
    String? registerDate,
    String? userType,
  }) {
    return ApiResponseDataModel(
      userID: userID ?? this.userID,
      emailAddress: emailAddress ?? this.emailAddress,
      fullName: fullName ?? this.fullName,
      profilePic: profilePic ?? this.profilePic,
      referralCode: referralCode ?? this.referralCode,
      registerDate: registerDate ?? this.registerDate,
      userType: userType ?? this.userType,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
       userID : userID,
       emailAddress : emailAddress,
       fullName : fullName,
       profilePic : profilePic,
       referralCode : referralCode,
       registerDate : registerDate,
       userType : userType,
    };
  }

  factory ApiResponseDataModel.fromMap(Map<String, dynamic> map) {
    return ApiResponseDataModel(
      userID: map[ userID ].toString(),
      emailAddress: map[ emailAddress ].toString(),
      fullName: map[ fullName ].toString(),
      profilePic: map[ profilePic ].toString(),
      referralCode: map[ referralCode ].toString(),
      registerDate: map[ registerDate ].toString(),
      userType: map[ userType ].toString(),
    );
  }

  String toJson() => json.encode(toMap());

  factory ApiResponseDataModel.fromJson(dynamic source) =>
      ApiResponseDataModel.fromMap(
          source as Map<String, dynamic>); // look here, i used dynamic
}

Future<List<ApiResponseModel>> login({required Map payload}) async {
  try {
    final List<ApiResponseModel> fetchList = [];
    final response = await apiService.postRequest(
      endpoint:  /user/auth/login ,
      data: payload,
    );
    if (response.statusCode == 200) {
      final result = json.decode(response.body) as List;
      for (var e in result) {
        fetchList.add(ApiResponseModel.fromJson(e));
      }
    } else {}
    return fetchList;
  } catch (err) {
    logger.log("Login Error: $err");
    rethrow;
  }
}

案件2

class ApiResponseModel {
  final int status_code;
  final String? status;
  final String? message;
  final ApiResponseDataModel data;
  ApiResponseModel({
    required this.status_code,
    this.status,
    this.message,
    required this.data,
  });

  ApiResponseModel copyWith({
    int? status_code,
    String? status,
    String? message,
    ApiResponseDataModel? data,
  }) {
    return ApiResponseModel(
      status_code: status_code ?? this.status_code,
      status: status ?? this.status,
      message: message ?? this.message,
      data: data ?? this.data,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
       status_code : status_code,
       status : status,
       message : message,
       data : data.toMap(),
    };
  }

  factory ApiResponseModel.fromMap(Map<String, dynamic> map) {
    return ApiResponseModel(
      status_code: map[ status_code ] as int,
      status: map[ status ] != null ? map[ status ].toString() : null,
      message: map[ message ] != null ? map[ message ].toString() : null,
      data: ApiResponseDataModel.fromMap(map[ data ] as Map<String, dynamic>),
    );
  }

  String toJson() => json.encode(toMap());

  factory ApiResponseModel.fromJson(dynamic source) =>
      ApiResponseModel.fromMap(source as Map<String, dynamic>);
}

class ApiResponseDataModel {
  final String userID;
  final String emailAddress;
  final String fullName;
  final String profilePic;
  final String referralCode;
  final String registerDate;
  final String userType;
  ApiResponseDataModel({
    required this.userID,
    required this.emailAddress,
    required this.fullName,
    required this.profilePic,
    required this.referralCode,
    required this.registerDate,
    required this.userType,
  });

  ApiResponseDataModel copyWith({
    String? userID,
    String? emailAddress,
    String? fullName,
    String? profilePic,
    String? referralCode,
    String? registerDate,
    String? userType,
  }) {
    return ApiResponseDataModel(
      userID: userID ?? this.userID,
      emailAddress: emailAddress ?? this.emailAddress,
      fullName: fullName ?? this.fullName,
      profilePic: profilePic ?? this.profilePic,
      referralCode: referralCode ?? this.referralCode,
      registerDate: registerDate ?? this.registerDate,
      userType: userType ?? this.userType,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
       userID : userID,
       emailAddress : emailAddress,
       fullName : fullName,
       profilePic : profilePic,
       referralCode : referralCode,
       registerDate : registerDate,
       userType : userType,
    };
  }

  factory ApiResponseDataModel.fromMap(Map<String, dynamic> map) {
    return ApiResponseDataModel(
      userID: map[ userID ].toString(),
      emailAddress: map[ emailAddress ].toString(),
      fullName: map[ fullName ].toString(),
      profilePic: map[ profilePic ].toString(),
      referralCode: map[ referralCode ].toString(),
      registerDate: map[ registerDate ].toString(),
      userType: map[ userType ].toString(),
    );
  }

  String toJson() => json.encode(toMap());

  factory ApiResponseDataModel.fromJson(dynamic source) =>
      ApiResponseDataModel.fromMap(
          source as Map<String, dynamic>); // look here, i used dynamic
}

Future<ApiResponseModel?> login({required Map payload}) async {
  try {
    ApiResponseModel? fetchList;
    final response = await apiService.postRequest(
      endpoint:  /user/auth/login ,
      data: payload,
    );
    if (response.statusCode == 200) {
      final result = json.decode(response.body);
      final item = ApiResponseModel.fromJson(result);
      fetchList = item;
    } else {}
    return fetchList;
  } catch (err) {
    logger.log("Login Error: $err");
    rethrow;
  }
}




相关问题
Finding a class within list

I have a class (Node) which has a property of SubNodes which is a List of the Node class I have a list of Nodes (of which each Node may or may not have a list of SubNodes within itself) I need to be ...

How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

Is List<> better than DataSet for UI Layer in ASP.Net?

I want to get data from my data access layer into my business layer, then prepare it for use in my UI. So i wonder: is it better to read my data by DataReader and use it to fill a List<BLClasses&...

What is the benefit to using List<T> over IEnumerable<T>?

or the other way around? I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at ...

灵活性:在滚动之前显示错误的清单

我有一份清单,在你滚动之前没有显示任何物品,然后这些物品就显示。 是否有任何人知道如何解决这一问题? 我尝试了叫人名单。

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签