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

Flutter调用API报type 'Null' is not a subtype of type 'String'错误求解决

问题原因

你遇到的type 'Null' is not a subtype of type 'String' in type cast报错,本质是Dart空安全机制下,API返回的部分字段为null,但代码中直接用as String将其强制转换为非空String类型,空值无法匹配非空类型要求触发报错。
常见的空字段场景包括分页接口第一页的previous字段、最后一页的next字段,以及内容可选的author、image_url等字段。

修复方案

1. 修正可空字段的类型转换逻辑

所有可能返回空值的字段,先转换为可空类型String?,再通过??设置兜底默认值,避免强制转换非空报错。

修改PostResponse.fromJson方法

factory PostResponse.fromJson(dynamic json) {
  print(json);
  return PostResponse(
    posts: (json['results'] as List).map((x) => Post.fromJson(x)).toList(),
    // 处理分页参数可能为空的情况
    nextUrl: json['next'] as String? ?? '',
    prevUrl: json['previous'] as String? ?? '',
  );
}

如果业务允许分页参数为空,也可以直接将模型属性改为可空类型:

class PostResponse {
  // 改为可空String,不需要强制非空
  String? nextUrl;
  String? prevUrl;
  List<Post> posts;

  PostResponse({
    this.nextUrl,
    this.prevUrl,
    required this.posts,
  });
  // 其余代码保持不变
}

修改Post.fromJson方法

factory Post.fromJson(dynamic json) => Post(
      title: json["title"] as String? ?? '无标题',
      content: json["content"] as String? ?? '无内容',
      imageUrl: json["image_url"] as String? ?? '',
      url: json["url"] as String? ?? '',
      category: Category.fromJson(json["category"]),
      // 先转可空类型再判空,避免转换报错
      author: json["author"] as String? ?? 'Admin',
      site: Site.fromJson(json["site"]),
      uploaded: json["uploaded"] as String? ?? '未知时间',
    );

2. 检查关联模型的转换逻辑

同步检查Category、Site模型的fromJson方法,如果存在同样的as String强制非空转换逻辑,也按照上述方法修改。

3. 修正主应用代码的泛型匹配

你的接口返回的是PostResponse类型,而FutureBuilder当前泛型设置为Post,类型不匹配也可能引发异常,修改为对应类型即可:

child: FutureBuilder<PostResponse>(
  future: _newsModel,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      // 示例:取返回列表第一篇文章的标题展示
      return Text(snapshot.data!.posts.first.title);
    } else if (snapshot.hasError) {
      return Text('${snapshot.error}');
    }
    return const Center(child: CircularProgressIndicator());
  },
)

内容的提问来源于stack exchange,提问作者Olaniyan Adewale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:06:00