0

I'm using freezed package to generate data classes.

The package support disabling the copyWith generation using @Freezed(copyWith: false) annotation.

I want to implement a custom copyWith to my Freezed data class. Here is my code:

@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, // resets if not provided
    );
  }
}

I generation runs successfully and there are no static analysis errors.

But when I run the app, I'm getting this error:

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.

What is the problem? How to implement custom copyWith in Freezed classes?

genericUser
  • 4,417
  • 1
  • 28
  • 73

1 Answers1

3

If you are adding methods to your freezed-model, as you are in this case, you have to define a private constructor.

So, add the line below, re-generate and everything should work:

const AuthenticationState._();

I.e.:

@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {

  const AuthenticationState._(); // ADD THIS LINE

  const factory AuthenticationState({
    String? userId,
    ErrorObject? errorObject,
  }) = _AuthenticationState;

  ...
}

This is a requirement posed by the freezed-package. See official documentation.

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • Why do I have to use private constructors? – genericUser Aug 31 '22 at 12:19
  • 1
    Because that is a requirement from the freezed package. I haven't read the source code myself, but I'm guessing that it is a requirement for the code generation to work properly. https://pub.dev/packages/freezed#adding-getters-and-methods-to-our-models – Robert Sandberg Aug 31 '22 at 12:42