将_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 LoginResponseModel {
  late bool success;
  late int status;
  late String message;
  late Map<String, dynamic> user;
  late String token;

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

  LoginResponseModel.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) => LoginResponseModel.fromjson(e)).toList();

错误输出

LoginResponseModael' 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
投票

你说:

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

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

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

相反,只需直接使用

fromJson

final response = LoginResponseModal.fromjson(response);

这是一个完整的可运行片段来演示:


import 'dart:convert';

void main() {
  final response = jsonDecode("""
{
  "success": true,
  "status": 200,
  "token": "...",
  "message": "you have logged in",
  "user": {"id": 1, "first_name": "..", "second_name": ".."}
}

""");
  final loginResponseModal = LoginResponseModal.fromjson(response);
  print(loginResponseModal.message);
}

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'];
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.