flutter _TypeError(type '(dynamic)=> User'不是'transform'的类型'(String,dynamic)=> MapEntry< dynamic,dynamic>'的子类型)

eiee3dmh  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(209)

我是Flutter的新手,并遵循教程link。然后我得到了TypeError,这里我使用http库来获取我使用node express创建的数据。
如果我使用来自jsonplaceholder假API,它可以工作,但在我自己的API中得到一个错误,为什么?
用户模型

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

String userToJson(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class User {
  int index;
  int id;
  String firstName;
  String lastName;
  String phone;
  String email;

  User({
    required this.index,
    required this.id,
    required this.firstName,
    required this.lastName,
    required this.phone,
    required this.email,
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
        index: json["index"],
        id: json["id"],
        firstName: json["first_name"],
        lastName: json["last_name"],
        phone: json["phone"],
        email: json["email"],
      );

  Map<String, dynamic> toJson() => {
        "index": index,
        "id": id,
        "first_name": firstName,
        "last_name": lastName,
        "phone": phone,
        "email": email,
      };
}

HTTP get方法

import 'package:http/http.dart' as http;

const String baseUrl = "http://192.168.166.153:5000/api/user";

class BaseClient {
  var client = http.Client();
  Future<dynamic> get(String api) async {
    var url = Uri.parse(baseUrl + api);
    var headers = {
      "autherization":
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNzZ2dAbW0uaW4iLCJpYXQiOjE2ODQ2NzEwMDEsImV4cCI6MTY4NDcyNTAwMX0.lTIIgHi7129dxvoI83sN82r5sHG88E8RGL2nsEimD1I",
    };

    var response = await client.get(url, headers: headers);
    if (response.statusCode == 200) {
      return response.body;
    } else {
      // else part
    }
  }
}


处出错
从REST API收到响应

{
    "responseCode": 200,
    "responseMessage": "Everything worked as expected",
    "responseData": [
        {
            "index": 2,
            "id": 1,
            "first_name": "oggy",
            "last_name": "ss",
            "phone": "1234567890",
            "email": "ss@ss.in"
        },
        {
            "index": 3,
            "id": 2,
            "first_name": "olly",
            "last_name": "ss",
            "phone": "1234567899",
            "email": "gg@gg.in"
        },
        {
            "index": 4,
            "id": 3,
            "first_name": "jack",
            "last_name": "jj",
            "phone": "1234567898",
            "email": "jj@jj.in"
        }
    ]
}
aelbi1ox

aelbi1ox1#

你的JSON不仅仅包括原始数组。所需的数组包含在一个JSON对象中,该对象还包含结果代码。
变更:

List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

致:

List<User>.from(json.decode(str)['responseData'].map((x) => User.fromJson(x)));

相关问题