modddels icon indicating copy to clipboard operation
modddels copied to clipboard

Directly create a case-modddel with preserved type

Open CodingSoot opened this issue 2 years ago • 3 comments

Freezed supports directly creating a union-case and preserving its type, for example :

@freezed
class MapLayer with _$MapLayer {
  const factory MapLayer.raster(int someParam) = Raster;

  const factory MapLayer.vector(int someParam) = Vector;

  const factory MapLayer.geojson(int someParam) = Geojson;
}

// then, instead of calling `MapLayer.raster(1)` :
final Raster raster = Raster(1);

In modddels, this is not supported (for now). If needed, you can cast the case-modddel directly after creating it, like this :

final raster = MapLayer.raster(
  //...
) as Raster;

Although it's pretty safe, it's not very clean so I'll look into implementing a better alternative.

Originally posted by @CodingSoot in https://github.com/CodingSoot/modddels/discussions/8#discussioncomment-6066086

CodingSoot avatar Jun 01 '23 23:06 CodingSoot

With the current implementation, all case-modddels are mixins, so they can't have factory constructors. This means we can't have a syntax like this :

final raster = Raster(1);

However, using static methods, we can have a syntax like this :

final raster = Raster.instance(1);

// or 
final raster = Raster.i(1);

This is much better than type-casting, but not very typical of Dart code. I'm not sure of the naming of the method though, would love some feedback before implementing this.

CodingSoot avatar Jun 03 '23 20:06 CodingSoot

This change should also apply to "ModddelParams" classes.

Right now, creating an instance of a case-modddel's ModddelParams was done like this :

final params = MapLayerParams.raster(1); // of type [_RasterParams]

Now, _RasterParams shouldn't be private anymore, and we should be able to directly create an instance of it.

final params = RasterParams(1); // of type [RasterParams]

// or maybe to keep the same syntax as for case-modddels : 
final params = RasterParams.instance(1);
//or
final params = RasterParams.i(1);

CodingSoot avatar Jun 03 '23 22:06 CodingSoot

With the current implementation, all case-modddels are mixins, so they can't have factory constructors.

With the new dart 3.0 class modifiers, we can do:

abstract mixin class Raster // ...

So we can have factory constructors.

CodingSoot avatar Jun 15 '23 13:06 CodingSoot