6thsolution / dart_sealed

Dart and Flutter sealed class generator and annotations, with match methods and other utilities. There is also super_enum compatible API.
https://pub.dev/packages/sealed_annotations
MIT License
17 stars 9 forks source link

Generate constant for types without arguments #14

Open Almighty-Alpaca opened 2 years ago

Almighty-Alpaca commented 2 years ago

In my project I have a sealed class with an empty subtype that I use as default argument in a constructor. For that to work I need a static constant of that type, which I currently have to create myself as a top level field. This PR allows the writer to generate those constants as static const field inside the sealed class.

Edit: I've noticed that my first commit didn't produce correct Dart code, so I've fixed that in the second one. Unfortunately for that I needed to remove the factory method that was previously generated for such subtypes, which is a breaking change. If this isn't acceptable, this could be solved with an optional parameter on the @Sealed() annotation controlling the code generation. But before I go there, I'll wait for feedback if this is a welcome addition at all here first.

Excerpt of generated code:

abstract class Weather {
  static const Weather sunny = WeatherSunny();

  const factory Weather.rainy({required int rain}) = WeatherRainy;
}
FatulM commented 7 months ago

Hi, in the standard generated code, we have:

abstract class Weather {
   const factory Weather.sunny() = WeatherSunny();

  const factory Weather.rainy({required int rain}) = WeatherRainy;
}

since we have constant factories, so you can use:

void doSomething({Weather arg = const Weather.sunny()}) {}