p69 / dartea

The Elm Architecture (TEA) for Flutter
MIT License
131 stars 15 forks source link

copyWith #6

Open dodyg opened 5 years ago

dodyg commented 5 years ago

Have you figured out a way to generate copyWith so it does not have to be created manually by hand? built_value offer this solution but it's pretty ugly to use.

p69 commented 5 years ago

Hi @dodyg , Well, actually I haven't thought about it. Yes, I agree with you that creating copyWith manually is not cool. I also feel uncomfortable while using built_value. How do you imagine the better approach? Dart doesn't provide much tools for such task. We can use code-generation, but something simpler than built_value. For example:

//create abstract class with properties and mark with special annotation, @record for example
@record
abstract class UserModel {
  int get age;
  String get name;
}

//Then corresponding class with constructor and copyWith will be generated.
class ImmutableUserModel implements UserModel {
  final int _age;
  final String _name;

  ImmutableUserModel(this._age, this._name);
  ImmutableUserModel copyWith({int age, String name}) {
    return ImmutableUserModel(
      age ?? this._age,
      name ?? this._name
    );
  }

  @override
  int get age => _age;

  @override
  String get name => _name;
}

What do you think?

dodyg commented 5 years ago

Sorry I missed this reply.

That sample looks promising. The code generator though needs to be able to deal with nested object otherwise we will all be stuck with flat object state.

Have you had any experience with dart code generation? I have not dug in on this part yet.