【问题标题】:Exception: type 'String' is not a subtype of type 'User' in type cast例外:类型“字符串”不是类型转换中“用户”类型的子类型
【发布时间】:2020-08-19 15:27:14
【问题描述】:

我正在尝试获取和显示帖子,但在从 json 提取数据时出现错误。

型号

class Post {
  final String id;
  final User author;
  final String caption;


  Post({this.id,this.author, this.caption, }
  );


  factory Post.fromJSON(Map<String, dynamic> jsonMap) {
    return Post(
      id: jsonMap['id'] as String,
      caption: jsonMap['caption'] as String,
      author: jsonMap['author'] as User,
   
    );
  }

  Map toMap(Post post) {
    var map = new Map<String, dynamic>();

    map["id"] = post.id;
    map["caption"] = post.caption;
    map["author"] = post.author;


    return map;
  }

  Map<String, dynamic> toJson() => {
  'id' : id,
  'author' :author,
  'caption' :caption,


  };
   String rawJson = jsonEncode(Map);

  @override
  String toString() {
    var map = this.toMap(Post());
    map["post"] = Post();
    return map.toString();
  }
}

我尝试使用

final String author;

而不是以前的版本

但是当我尝试它时它也给了我

Converting object to an encodable object failed: Map<dynamic, dynamic>

我需要将其声明为 User 而不是 String,因为我需要在帖子中访问作者的信息(用户名、id 等)

有没有人可以解决这个问题?

更新 1: 我从 Json Server 获得“用户”引用,因此我必须将其称为用户,以便可以引用“User.email”等内容。 我有这样声明的用户

class User {
  final String id;
  final String email;
  final String username;

 User({
    this.id,this.email,this.username,
  });


  factory User.fromJSON(Map<String, dynamic> json) {
    return User(
      id: json['id'] as String,
      email: json['email'] as String,
      username: json['username'] as String,
    );
  }

  Map<String, dynamic> toJson() => {
    'id' : id,
    'email' : email,
    'username' : username,



  };

  Map toMap(User user) {
    var map = new Map<String, dynamic>();
    map["id"] = user.id;
    map["email"] = user.email;
    map["username"] = user.username ;


    return map;
  }


  @override
  String toString() {
    var map = this.toMap(User());
    map["user"] = User();
    return map.toString();
  }
}

更新 2:

Future<List<Post>> fetchPosts(http.Client client) async {
  final response = await http.get("$SERVER_IP/api/articles/?format=json");

  return compute(parsePosts, response.body);
}
List<Post> parsePosts(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<Post>((json) => Post.fromJSON(json)).toList();
}

更新 3: 这是我从作者(它通过 id 引用作者)和 id 获得的 UUID。 顺便说一句,你知道它不是 firebase,它是 Django,所以我不能使用任何与 firebase 相关的代码。

[
    {
        "id": "3ab6e7c8-6a4c-42c2-a08d-e8a6c0fcdecb",
        "author": "dbb0446d-d0ec-4c24-9c1e-8ca9b6b06a7d",
        "caption": "caption here",
       
    }
]

【问题讨论】:

  • 请发布您的响应 JSON 我会修复它
  • 检查更新 2。
  • 没关系,但我想查看您从 API 发送 response.body 获得的 JSON 数据
  • 请检查更新 3。

标签: flutter


【解决方案1】:

你不能那样做,因为它仍然是一张地图!

例如,在User 类中解决这个问题的方法是(我已经编好了属性!):

class User {
    String name;
    String lastName;

    const User({
        this.name,
        this.lastName,
    });

    factory User.fromJson(Map<String, dynamic> json) {
        return User(
            name: json['name'],
            lastName: json['lastName'],
        );
    }
}

这里使用了 factory 构造函数(再次),但现在我们将 json 数据(或地图)解析为 User。然后在Post JSON 构造函数中你必须使用User JSON 构造函数。

【讨论】:

  • 检查更新 1 。我之前已经声明了我的用户,与您编写的代码相比,我看不出有什么不同?
  • 嗯,有。您不必强制转换用户。你必须这样做:author: User.fromJson(jsonMap['author])Post 构造函数中。你正在做一个cast,在这种情况下是不正确的。强制转换用于将一种类型转换为另一种类型,而不是创建对象,您必须创建 User 对象。
  • 现在我收到错误type 'String' is not a subtype of type 'Map&lt;String, dynamic&gt;'
  • 是什么导致了错误?请您也可以在问题中添加print(response.body) 吗?
  • 我意识到更新作者final String author; , Map 是由另一个变量引起的。所以我看到这个案子解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 2020-07-02
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2021-10-22
相关资源
最近更新 更多