ivnsch / dart_copy_with_plugin

Dart copyWith generation plugin
MIT License
8 stars 0 forks source link

improvment adding an option to generate a empty() method #3

Open me-zo opened 1 year ago

me-zo commented 1 year ago

Hi i've been using this plugin for a while and one thing bothered me so i thought id check if adding it is possible, a common method we use is the empty() function when using data classes is it possible to add that into the plugin so it generates it along with the copyWith() option.

dinbtechit commented 1 year ago

Can you provide some code examples?

me-zo commented 1 year ago

yes sure, basically the output will look like this.


class OtherModel {
  const OtherModel();
  static const OtherModel empty = OtherModel();
}

class Model {
  final int someInt;
  final String someString;
  final OtherModel someOtherModel;

  const Model({
    required this.someInt,
    required this.someString,
    required this.someOtherModel,
  });

  static const Model empty = Model(
    someInt: 0,
    someString: "",
    someOtherModel: OtherModel.empty,
  );
}
me-zo commented 1 year ago

I've changed it to be a const var so it can be used by other constructors

dinbtechit commented 1 year ago

oh, you mean a default value for each member variable. I am not sure how far this is practical. What if the SomeOtherModel class was inside a 3rd party library. It would not have the method empty() in it.

I think we could do something like this but it will have compile errors. Until you provide a default value for each member variable.

const Model.defaultValue({
  this.someInt = /*Provide Default Value*/,
  this.someString = /*Provide Default Value*/,
  this.someOtherModel = /*Provide Default Value*/
});
me-zo commented 1 year ago

yeah I understand your concern however this is only useful in data classes where Model and SomeOtherModel are either Dtos, Models, or Entities. so in the case one of them is in a package, the user will need to handle it. but in most cases these will be passed as parameters in the UI layer or inside ViewModels. so having them without a any parameters and as constants is essential. as for the name, default is a better name than empty for sure.

dinbtechit commented 1 year ago

I just realized you can't use default as it is a reserved keyword. I also simplified the code in my answer. But I guess you can create a named argument constructor and pass in the default values.

const Model.defaultValue({
  this.someInt = /*Provide Default Value*/,
  this.someString = /*Provide Default Value*/,
  this.someOtherModel = /*Provide Default Value*/
});

image

This is one of the use cases that can be solved using the upcoming feature in Dart 3 Macros/static metaprogramming.