rrousselGit / freezed

Code generation for immutable classes that has a simple syntax/API without compromising on the features.
https://pub.dev/packages/freezed
1.92k stars 236 forks source link

Issue with copyWith method generation in Freezed #1003

Closed oyen-bright closed 11 months ago

oyen-bright commented 11 months ago

I am encountering an issue with the copyWith method generation in the Freezed package. Upon generating the Freezed code, the copyWith method is not being automatically created as expected, resulting in manual implementation errors.

The Freezed package should automatically generate the copyWith method for all the properties declared in the class, allowing for easy updates to the immutable state.

The copyWith method is not automatically generated, leading to errors and manual implementation difficulties.

Version of Freezed package: 2.4.5

@freezed class WalletState with _$WalletState { const factory WalletState.noWallet() = NoWallet; const factory WalletState.hasWallet({ required bool isConnected, required String? walletAddress, }) = HasWallet;

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

rrousselGit commented 11 months ago

There is a copyWith available. But you have to cast WalletState to HasWallet

Since NoWallet has no properties at all, there's nothing to clone for that case. As such there's no copyWith possible from the WalletState interface.

oyen-bright commented 11 months ago

What if I simply want to update the isConnected status within WalletState.hasWallet? Can't I use the state.copyWith() method? I am currently utilizing the Flutter BLoC pattern. Please provide a code example as I am new to the 'freezed' package.

Future<String?> disconnectWallet() async { final response = await walletRepository.disconnectWallet(); if (response.$1 != null) { return response.$1; } else { emit(state.copyWith(isConnected:false); // this is not working, there's no copy with method on the walletstate } return null; }

@rrousselGit

rrousselGit commented 11 months ago

Like I said, you have to cast your object to `HasWallet:

(state as HasWallet).copyWith
oyen-bright commented 11 months ago

alright thanks