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

Freezed类自定义copyWith运行报错,求问题原因及实现方法

问题描述

我使用Freezed包生成数据类,通过@Freezed(copyWith: false)注解禁用了自动生成的copyWith方法,尝试自行实现自定义copyWith方法,代码如下:

@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {
  const factory AuthenticationState({
    String? userId,
    ErrorObject? errorObject,
  }) = _AuthenticationState;

  AuthenticationState copyWith({
    String? userId,
    ErrorObject? errorObject,
  }) {
    return AuthenticationState(
      userId: userId ?? this.userId,
      errorObject: errorObject, // 不传入则重置
    );
  }
}

代码生成成功且无静态分析错误,但运行应用时出现报错:

authentication_bloc.freezed.dart:32:7: Error: The non-abstract class
'_$_AuthenticationState' is missing implementations for these members:

  • AuthenticationState.copyWith Try to either
  • provide an implementation,
  • inherit an implementation from a superclass or mixin,
  • mark the class as abstract, or
  • provide a 'noSuchMethod' implementation.
    class _$_AuthenticationState implements _AuthenticationState {
    ^^^^^^^^^^^^^^^^^^^^^^ lib/authentication/bloc/authentication_state.dart:28:23: Context:
    'AuthenticationState.copyWith' is defined here.
问题原因

Freezed的代码生成机制决定了:你编写的AuthenticationState会被处理为抽象类,生成的具体实现类_$_AuthenticationState是实现_AuthenticationState接口,而非直接继承AuthenticationState类。你在AuthenticationState中定义的copyWith实例方法,不会被生成的子类自动继承或实现,因此运行时会提示子类缺少该方法的实现逻辑。

解决方法

最优方案是使用扩展方法实现自定义copyWith,这是Freezed中添加自定义实例方法的标准方式,不会与生成代码产生冲突:

@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {
  const factory AuthenticationState({
    String? userId,
    ErrorObject? errorObject,
  }) = _AuthenticationState;
}

// 通过扩展为AuthenticationState添加自定义copyWith方法
extension AuthenticationStateCopyWith on AuthenticationState {
  AuthenticationState copyWith({
    String? userId,
    ErrorObject? errorObject,
  }) {
    return AuthenticationState(
      userId: userId ?? this.userId,
      errorObject: errorObject, // 不传入参数则重置为null
    );
  }
}

这种方式下,所有AuthenticationState的实例都能正常调用copyWith方法,且不会触发子类未实现方法的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:57:31