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

Flutter中使用Freezed结合json_serializer时出现未实现方法的报错求助

Flutter中使用Freezed结合json_serializer时出现未实现方法的报错求助

大家好,我最近在Flutter项目里尝试用Freezed配合json_serializer来解析API返回的JSON数据,结果遇到了一些麻烦,想请教下各位开发者!

问题背景

我需要解析的SendOTP接口返回的JSON结构是这样的:

{ 
  "CustomData": { 
    "message": "OTP sent successfully", 
    "msisdn": "1273" 
  } 
}

我按照Freezed的规范写了对应的实体类代码,文件名为send_otp_response.dart,代码如下:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'send_otp_response.freezed.dart';
part 'send_otp_response.g.dart';

@freezed
class SendOtpResponse with _$SendOtpResponse {
  const factory SendOtpResponse({
    @JsonKey(name: 'CustomData') required CustomData customData,
  }) = _SendOtpResponse;

  factory SendOtpResponse.fromJson(Map<String, dynamic> json) => _$SendOtpResponseFromJson(json);
}

@freezed
class CustomData with _$CustomData {
  const factory CustomData({
    @Default('') String message,
    @Default('') String msisdn,
  }) = _CustomData;

  factory CustomData.fromJson(Map<String, dynamic> json) => _$CustomDataFromJson(json);
}

之后我也运行了生成代码的命令:

flutter packages pub run build_runner watch --delete-conflicting-outputs

遇到的问题

虽然命令运行看起来正常,但在IDE里鼠标悬停在类上时还是出现了报错提示:

  • 悬停SendOtpResponse时,提示:Missing concrete implementations of '_$SendOtpResponse.toJson' and 'getter _$SendOtpResponse.customData'
  • 悬停CustomData时,提示:Missing concrete implementations of '_$CustomData.toJson', 'getter _$CustomData.message', and 'getter _$CustomData.msisdn'

我已经确认了类名和文件名的对应关系,也确保命令执行时没有明显的终端报错,但就是解决不了这些提示,有没有朋友知道这是哪里出问题了?

我尝试过的排查步骤(未解决)

  • 确认.g.dart生成文件存在,且里面有对应代码
  • 重复停止并重启build_runner命令
  • 检查@JsonKey的键名和API返回的JSON键完全匹配

希望大家能给我一些排查的思路或者解决办法,谢谢啦!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 08:23:05