将_map<string,dynmic>转换为flutter中的模态

问题描述 投票:0回答:1

我有以下记录来自API

{
success: true
status: 200,
token: "...",
message: "you have logged in"
user: {id:1, first_name: "..", second_name: "..",}
}

它是一条单条记录,数据类型为_map

这是我的模式

class LoginResponseModal {
  late bool success;
  late int status;
  late String message;
  late Map<String, dynamic> user;
  late String token;

  LoginResponseModal(
      {required this.success,
      required this.status,
      required this.message,
      required this.user,
      required this.token});

  LoginResponseModal.fromjson(Map<String, dynamic> json) {
    success = json['success'];
    status = json['status'];
    message = json['message'];
    user = json['user'];
    token = json['token'];
  }
}

我需要将来自 API 且数据类型为 _map 的记录转换为模态,这里是我所做的

  var test1 = response.map((e) => LoginResponseModal.fromjson(e)).toList();

错误输出

LoginResponseModal' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

也用过

var parsedJson = jsonDecode(response);

错误输出

type '_Map<String, dynamic>' is not a subtype of type 'String'
flutter dart types
1个回答
0
投票

你说:

它是一条

single
记录,数据类型为_map

由于这是一条记录,因此您不应使用

.map
来调用
response.map((e)

相反,只需使用

fromJson
目录即可:

final response = LoginResponseModal.fromjson(response);
© www.soinside.com 2019 - 2024. All rights reserved.