【问题标题】:'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' Flutter [duplicate]'List<dynamic>' 不是'Map<String, dynamic>' Flutter 类型的子类型 [重复]
【发布时间】:2021-07-11 20:48:36
【问题描述】:

在这里,我正在尝试创建一个未来的列表视图构建器,收到一条错误消息:_TypeError (type 'List' is not a subtype of type 'Map') 颤动。我需要在列表视图中获取帖子中的所有数据。使用 JSON 到 dart 转换器 quicktype.io 创建模型类

未来的召唤

Future<Posts> getPosts() async {
  try {
    final response =
        await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));

    var data = jsonDecode(response.body);
    return Posts.fromJson(data);
  } catch (e) {
    print(e);
  }
}

型号

List<Posts> postsFromJson(String str) => List<Posts>.from(json.decode(str).map((x) => Posts.fromJson(x)));
String postsToJson(List<Posts> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Posts {
    Posts({
        this.userId,
        this.id,
        this.title,
        this.body,
    });

    int userId;
    int id;
    String title;
    String body;

    factory Posts.fromJson(Map<String, dynamic> json) => Posts(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
    );

    Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
    };
}


【问题讨论】:

    标签: flutter dart flutter-web


    【解决方案1】:

    改变这个:

    var data = jsonDecode(response.body);
    

    进入这个:

    var data = (jsonDecode(response.body) as List<dynamic>).cast<Map<String, dynamic>>();
    

    【讨论】:

      【解决方案2】:

      我认为您的 API 返回的帖子列表不仅仅是一个帖子。首先我建议将您的班级名称从 Posts 重命名为 Post 然后下面的代码可以解决您的问题:

      Future<List<Posts>> getPosts() async {
        try {
          final response =
              await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));
      
          var data = jsonDecode(response.body);
          return data.map<Posts>((data) => Posts.fromJson(json.decode(data))).toList();
        } catch (e) {
          print(e);
        }
      }
      

      【讨论】:

        【解决方案3】:

        我认为你应该使用:

        return postsFromJson(data);
        

        并使该函数返回一个列表,因为在您的响应正文中它返回一个对象列表,因此仅使用 Posts.fromJson() 会给您这个错误,因为 Posts.fromJson() 需要一个 Map,而您给了它一个列表。如果您只想要一个项目,您可以访问列表中的该项目并将其提供给 Posts.fromJson() 函数

        【讨论】:

          猜你喜欢
          • 2023-01-07
          • 2021-06-09
          • 2019-08-18
          • 2021-12-02
          • 2021-04-06
          • 2019-09-02
          • 2021-12-29
          • 2023-01-08
          相关资源
          最近更新 更多