You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter类型转换报错:bool并非List<Post>的子类型

问题解决:type 'bool' is not a subtype of type 'List' in type cast

错误原因

你犯了一个基础错误:snapshot.hasData是布尔类型,仅用于判断快照是否包含有效数据,并非实际的数据源。你却把它当作List<Post>进行强制类型转换,这必然会触发类型不匹配的报错。

修正步骤

  1. 替换数据源:将snapshot.hasData改为snapshot.data,这才是存储实际请求数据的属性。
  2. 正确转换数据类型:如果接口返回的是JSON数组(即List<Map<String, dynamic>>),不能直接强转为List<Post>,需要通过Post类的fromJson构造方法逐个转换元素。

修正后的完整代码示例

if (snapshot.hasData) {
  // 获取原始JSON数组数据
  List<dynamic> rawPosts = snapshot.data as List<dynamic>;
  // 转换为Post对象列表
  List<Post> posts = rawPosts.map((json) => Post.fromJson(json)).toList();

  return ListView(
    children: posts
        .map((Post post) => ListTile(
              title: Text(post.title),
              subtitle: Text(post.id.toString()),
              onTap: () => Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => PostDetails(post: post))
              ),
            ))
        .toList(), // 注意:map返回Iterable,需要转为List才能作为ListView的children
  );
}

确保Post类包含fromJson构造方法

你的Post类必须实现从JSON到对象的转换逻辑,示例如下:

class Post {
  final int id;
  final String title;

  Post({required this.id, required this.title});

  // 从JSON构造Post对象
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] as int,
      title: json['title'] as String,
    );
  }
}

内容的提问来源于stack exchange,提问作者Zubair Naeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:21:06