jankuss / genq

Instant Data Class Generation for Dart
MIT License
133 stars 0 forks source link

Support sealed classes #29

Closed BWhiteApps closed 4 months ago

BWhiteApps commented 4 months ago

One change that would make genq an excellent freezed replacement would be to support unions with sealed classes. Example

@genq
sealed class HomeState with _$HomeState {
  const factory HomeState.loading() = LoadingState;
  const factory HomeState.loaded(String data) = LoadedState;
  const factory HomeState.error(String message) = ErrorState;
}

It would be great if this was able to generate a sealed classes that could be used with dart's pattern matching. Here is more details on how this would be useful: https://medium.com/@aliammariraq/sealed-classes-in-dart-unlocking-powerful-features-d8dba185925f

jankuss commented 4 months ago

If you require sealed classes, genq already supports the following:

import 'package:genq/genq.dart';

part 'input.genq.dart';

sealed class State {}

@genq
class LoadingState extends State with _$LoadingState {
  const factory LoadingState() = _LoadingState;
}

@genq
class SuccessState extends State with _$SuccessState {
  const factory SuccessState({
    required String name,
    required int age,
  }) = _SuccessState;
}

void main() {
  final State state = LoadingState();

  final result = switch(state) {
    LoadingState() => 'Loading',
    SuccessState(name: 'John', age: 30) => 'A 30 year old John',
    SuccessState(name: final name, age: 1) => '$name is just 1 year old',
    SuccessState(name: final name, age: final age) => '$name is $age years old',
  };

  print(result);
}

It definetly is not as pretty as the requested syntax, but works if you need sealed classes. Regarding the requested syntax, #30 tracks this feature request. So I will close this for now.