Home > OS >  Flutter How to implement custom `copyWith` in Freezed classes? (@Freezed(copyWith: false))
Flutter How to implement custom `copyWith` in Freezed classes? (@Freezed(copyWith: false))

Time:09-01

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?

CodePudding user response:

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.

  • Related