Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minimal implementation to support derived-class copy-with overriding #90

Conversation

Adam-Langley
Copy link

Resolves #87 and #65

Current production copy_with_generator does not honor derivation of classes annotated with CopyWith. This means that given class A (copyWith) derived by class B (also copyWith) when an instance of B is cast to A, calling 'copyWith' will return an instance of class A, losing all of the properties of B.

It's clear this can cause issues unless the developer is cognisant.
My specific use case is where copyWith is used to mutate state in Flutter Bloc applications.

When Blocs are responding to events, every event receives the current state as the bloc-declared archetype state (i.e. MyInitialState). The the event handler will cast the state to the class that it is aware of - even though it may currently be an instance of a derived type. When calling "copyWith" all derived values are lost.

Usage

After regenerating your code with this enhancement, add override capabilities to your classes like so:

// ignore_for_file: library_private_types_in_public_api
// required to expose copyWith

@CopyWith()
final class InitialState {
  final int id;
  final String name;

  const InitialState({
    required this.id, 
    required this.name,
  });

  // classes must now declare the 'copyWith' method like so
  _$InitialStateCWProxy get copyWith => _$InitialStateCWProxyImpl(this);
}

@CopyWith()
final class ErroredState extends InitialState {
  final String errorMessage;

  const ErroredState({
    required super.id, 
    required super.name,
    required this.errorMessage,
  });

  // classes must now declare the 'copyWith' method like so. Note how it declares and returns the proxy for THIS class.
  // this is now legal because the enhanced generator declares a inherited relationship between the CWProxy interfaces
  @override
  _$ErroredStateCWProxy get copyWith => _$ErroredStateCWProxyImpl(this);
}

Effect

Here is a pseudo-code usage example for the above example

InitialState state = ErroredState(id: 1, name: 'name', errorMessage: 'error message');
var newState = state.copyWith(name: 'new name');
print('new state');

// output will be 'ErroredState(id: 1, name: 'new name', errorMessage: 'error message');

Caveats

The PR is indeed a minimal implementation. Some cases not handled are:

  1. Generated code for derived classes will still contain definitions for the supertypes members. These are now redundant, and will produce warnings that they are overrides but do not declare @OverRide. This is benign.

josiahsrc and others added 28 commits June 24, 2021 17:18
* added nullability for generic parameter constraints

* added nullability check for typing nullables
* analyzer version is set to 2.0.0

* ci minor corrections

* ci corrections

* a possible build fix

* minor ci correction

* changelog

* minor
* Switching to flutter_lints + null safety code cleanup

* CI corrections

* named constructor feature
* basic implementation

* minor

* prevent unnecessary copyWithNull methods generation

* naming corrections

* naming + ignore cast_nullable_to_non_nullable

* docs + test fixes

* docs

* docs

* release
* fix for copyWith null for a non-nullable value

* version bump

* minor ci correction

* minor ci correction
* Updating analyser version

* Release notes
* Lint correction

* tests correction
* feat(settings): create settings class with default values

* refactor(settings): remove default values in favor of settings from build.yaml

* feat(settings): get settings from config and make available globally

* refactor(settings): change type of #readClassAnnotation to `CopyWithAnnotation` to assert values

* feat: create pubspec overrides to always read from project

* feat(target annotation): annotate copy_with annotations with Target for better linting

* style: organize code (alphabetize)

* feat(positioned): add `isPositioned` property to `FieldInfo`

* refactor(positioned): remove positional check and unneeded sort

* feat(positioned): add check for positioned to include param name

* feat: add tests for positioned fields

* refactor(positioned): remove named field exceptions tests

* feat(positioned): add set settings for testing

* fix(positioned): tests for positioned params

* feat(field): create `CopyWithFieldAnnotation`

* feat(field): remove default values in favor of `CopyWithFieldAnnotation` default values

* refactor(field): remove `immutable` prop and replace with `fieldAnnotation`

* refactor(fields) reference new `fieldAnnotation` prop for immutable

* feat(nullable): add check for null args and add ignores for file

* fix: tests to include new additions

* docs: update readme
* removing global Settings object + testing global settings

* sort_constructors_first

* tests fix

* minor corrections

* version bump to 5.0.0 to avoid compatibility issues

* minor corrections
* Update copy_with_generator.dart

* Update pubspec.yaml

* remove unnecessary ignore comment.

* removed unnecessary cast_nullable_to_non_nullable comment

* Update pubspec.yaml

* Update copy_with_generator.dart

removed unnecessary ! cast

* Update pubspec.yaml

* Update copy_with_generator.dart

! for non nullable fields

* Update pubspec.yaml

* Update copy_with_generator.dart

* Update pubspec.yaml

* Update copy_with_generator.dart

* Update pubspec.yaml
* test to cover all mentioned nullability issues

* minor

* minor

* ci correction

* use analyse action to output errors correctly to the CI dashboard actions

* minor corrections

* crashing dynamic test case

* minor

* show warnings from "dart run test"

* Revert "show warnings from "dart run test""

This reverts commit f0d4ae3.

* introspecting the class itself about the relevant constructors parameters

* have ! only when the field of the class is non-nullable

* Roll back feature with nullable field and non-nullable constructor.

* tests + introducing an error when fields nullability not in sync with the constructor

* remove question mark from dynamic input parameters

* version bump
* Fixing use case described in numen31337#79

* version bump

* test fix
* migrate to dart 3

* fix a small issue related to dart 3
Current production copy_with_generator does not honour derivation of classes annotated with CopyWith.
This means that given class A (copyWith) derived by class B (also copyWith) when an instance of B is cast to A, calling 'copyWith' will return an instance of class A, losing all of the properties of B.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

"CopyWithable" type for a extended child at the compile time