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

copyWith #6

Open
dodyg opened this issue Nov 28, 2018 · 2 comments
Open

copyWith #6

dodyg opened this issue Nov 28, 2018 · 2 comments

Comments

@dodyg
Copy link

dodyg commented Nov 28, 2018

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
Copy link
Owner

p69 commented Nov 28, 2018

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
Copy link
Author

dodyg commented Dec 5, 2018

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.

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

No branches or pull requests

2 participants