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

Flutter解析RapidAPI嵌套JSON遇Null转List<dynamic>错误求助

解决Dart嵌套JSON解析的类型转换错误

核心错误原因

你遇到的type "null" is not a subtype of type 'List<dynamic>' in type cast错误,是因为API返回的instructions字段可能为null,但代码直接将其强制转换为List,未处理null场景。

完整修复方案

1. 修正基础语法与命名规范

  • Dart类名需遵循大驼峰规范,首字母大写;
  • Map<"String", dynamic>写法错误,应改为Map<String, dynamic>,去掉多余引号;
  • 对所有可能为null的字段做可空处理,避免后续类型错误。

修复后的完整代码

Recipe类

class Recipe {
  final String? image;
  final Rating? rating;
  final int? time;
  final int? personNum;
  final String? name;
  final String? description;
  final List<Instruction> instructions;

  Recipe({
    this.image,
    this.rating,
    this.time,
    this.personNum,
    this.name,
    this.description,
    required this.instructions,
  });

  factory Recipe.fromJson(Map<String, dynamic> json) {
    // 处理instructions为null的情况,默认返回空列表
    final instructionsRaw = json['instructions'] as List<dynamic>? ?? [];
    List<Instruction> instructionList = instructionsRaw
        .map((item) => Instruction.fromJson(item as Map<String, dynamic>))
        .toList();

    return Recipe(
      image: json['thumbnail_url'],
      rating: json['user_ratings'] != null 
          ? Rating.fromJson(json['user_ratings'] as Map<String, dynamic>) 
          : null,
      time: json['total_time_minutes'],
      name: json['name'],
      description: json['description'],
      instructions: instructionList,
      personNum: json['num_servings'],
    );
  }
}

Rating类

class Rating {
  final int? score;

  Rating({this.score});

  factory Rating.fromJson(Map<String, dynamic> json) {
    return Rating(
      score: json['score'] as int?,
    );
  }
}

Instruction类

class Instruction {
  final int? stepNum;
  final String? text;

  Instruction({this.text, this.stepNum});

  factory Instruction.fromJson(Map<String, dynamic> json) {
    return Instruction(
      text: json['display_text'],
      stepNum: json['position'] as int?,
    );
  }
}

关键修复点说明

  • null安全处理:用?? []运算符,当instructions字段为null时默认返回空列表,避免强制转换错误;
  • 可空字段兼容:将score、image、stepNum等可能为null的字段改为可空类型,适配API返回的不确定场景;
  • 编码规范修正:统一类名大驼峰格式,修正泛型写法,符合Dart语言编码标准。

内容的提问来源于stack exchange,提问作者Alaa Abdullah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:14:55