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

huangapple go评论61阅读模式
英文:

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

问题

I'm here to provide translations. Here's the translated content:

我是Flutter的新手,正在按照教程链接操作。我遇到了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 = {
      "authorization":
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNzZ2dAbW0uaW4iLCJpYXQiOjE2ODQ2NzEwMDEsImV4cCI6MTY4NDcyNTAwMX0.lTIIgHi7129dxvoI83sN82r5sHG88E8RGL2nsEimD1I",
    };

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

错误发生在_TypeError (type '(dynamic) => User' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')

从REST API接收到的响应

{
    "responseCode": 200,
    "responseMessage": "一切都按预期进行",
    "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"
        }
    ]
}
英文:

I'm new to Flutter and following the tutorial link. and I get the TypeError, here I have used http library to fetch the data that I have created using node express.

if I use fake API from jsonplaceholder it works but get an error in my own API why?

user model

import &#39;dart:convert&#39;;

List&lt;User&gt; userFromJson(String str) =&gt;
    List&lt;User&gt;.from(json.decode(str).map((x) =&gt; User.fromJson(x)));

String userToJson(List&lt;User&gt; data) =&gt;
    json.encode(List&lt;dynamic&gt;.from(data.map((x) =&gt; 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&lt;String, dynamic&gt; json) =&gt; User(
        index: json[&quot;index&quot;],
        id: json[&quot;id&quot;],
        firstName: json[&quot;first_name&quot;],
        lastName: json[&quot;last_name&quot;],
        phone: json[&quot;phone&quot;],
        email: json[&quot;email&quot;],
      );

  Map&lt;String, dynamic&gt; toJson() =&gt; {
        &quot;index&quot;: index,
        &quot;id&quot;: id,
        &quot;first_name&quot;: firstName,
        &quot;last_name&quot;: lastName,
        &quot;phone&quot;: phone,
        &quot;email&quot;: email,
      };
}

HTTP get method

import &#39;package:http/http.dart&#39; as http;

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

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

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

Error occurs at _TypeError (type '(dynamic) => User' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')

response received form REST API

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

答案1

得分: 1

将以下内容翻译为中文:

"Your JSON doesn't just include the raw array. The array you want is contained inside a JSON object that also contains the result code.

Change:

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

to:

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

请注意,代码部分未被翻译。

英文:

Your JSON doesn't just include the raw array. The array you want is contained inside a JSON object that also contains the result code.

Change:

List&lt;User&gt;.from(json.decode(str).map((x) =&gt; User.fromJson(x)));

to:

List&lt;User&gt;.from(json.decode(str)[&#39;responseData&#39;].map((x) =&gt; User.fromJson(x)));

huangapple
  • 本文由 发表于 2023年5月21日 20:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定