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

Flutter中Isar搭配Freezed使用时build_runner报Unsupported type错误

Flutter中Isar与Freezed集成时build_runner的copyWith类型错误修复

问题场景

在Flutter项目中同时使用Isar数据库和Freezed进行代码生成时,执行flutter pub run build_runner build命令会报错,提示copyWith getter存在不支持的类型,要求用@ignore标注。

错误代码示例

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:isar/isar.dart';

part 'api_response_model.freezed.dart';
part 'api_response_model.g.dart';

@collection
@freezed
class ApiResponseModel with _$ApiResponseModel {
  const ApiResponseModel._();

  factory ApiResponseModel({
    @JsonKey(name: 'data') String? data,
  }) = ResponseModel;

  Id get id => Isar.autoIncrement;

  factory ApiResponseModel.fromJson(Map<String, Object?> json) =>
      _$ApiResponseModelFromJson(json);
}

错误信息

Unsupported type. Please annotate the property with @ignore.
package:freezed_isar/api_response_model.freezed.dart:28:51
   ╷
28 │   $ApiResponseModelCopyWith<ApiResponseModel> get copyWith =>
   │                                                   ^^^^^^^^
   ╵

解决方法

问题根源是Freezed自动生成的copyWith getter的类型不属于Isar支持的数据库存储类型,需要告诉Isar忽略这个属性。

有两种可行的修复方式:

方式一:修改@collection注解,指定忽略copyWith

直接在@collection注解中添加ignore参数,明确忽略copyWith属性:

@collection(ignore: {'copyWith'})
@freezed
class ApiResponseModel with _$ApiResponseModel {
  // 类内容保持不变
}

方式二:显式给copyWith添加@ignore注解

在类中显式声明copyWith getter并标注@ignore,覆盖Freezed生成的版本:

@collection
@freezed
class ApiResponseModel with _$ApiResponseModel {
  const ApiResponseModel._();

  factory ApiResponseModel({
    @JsonKey(name: 'data') String? data,
  }) = ResponseModel;

  Id get id => Isar.autoIncrement;

  @ignore
  @override
  $ApiResponseModelCopyWith<ApiResponseModel> get copyWith => super.copyWith;

  factory ApiResponseModel.fromJson(Map<String, Object?> json) =>
      _$ApiResponseModelFromJson(json);
}

两种方式都能让Isar跳过对copyWith的类型校验,顺利完成代码生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:05:07