Skip to content

[REQ][DART-DIO] copyWith extension for json_serializable as the serializationLibrary #21665

@LahaLuhem

Description

@LahaLuhem

Is your feature request related to a problem? Please describe.

The default 'built_value' provides a builder pattern to 'rebuild' an object with modified properties. The 'json_serializable' option for the dart-dio generator generates completely frozen classes and in doing so, one has to mutate objects in a cumbersome way like so: final model2 = Model(model1.elem1, model1.elem2 + 1).

Describe the solution you'd like

Dart already leverages a common copyWith pattern to maintain immutability.
copyWithExtension package exists to generate a copyWith in the same part file. So the model classes can be annotated with the @CopyWith() annotation, in addition to the @JsonSerializable() annotation. The generated model/dtos would then have a generated copyWith() method in the same part file as the json_serializable's boilerplate. This would then more closely match the functionality given by default 'built_value' serialization library.

Describe alternatives you've considered

Post generation, I have run the following script to:

  1. Add the dependencies to pubspec.yaml
  2. Add the @CopyWith() to each class in the models directory
  3. Rerun the build_runner
# Annotate every class with `CopyWith`
find lib/src/model -type f -name '*.dart' | while read -r file; do
# Insert import if missing
grep -q "copy_with_extension" "$file" || sed -i '' "/package:json_annotation/a\\
import 'package:copy_with_extension/copy_with_extension.dart';
" "$file"

# Insert @CopyWith() if missing
grep -q "@CopyWith" "$file" || sed -i '' "/@JsonSerializable/i\\
@CopyWith()
" "$file"
done

Additional context

The default 'built_value' already provide a safe way to maintain immutability and this other implementation should atleast match in terms of it

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions