like_sealed_gen

This package generates utils for comfortable work with sealed classes

Sealed class

Create sealed class like this

    import 'package:like_sealed/like_sealed.dart';
    
    part 'state.sealed.dart';
    
    @LikeSealed(switchImpl: true)
    abstract class State {}
    
    class StateData extends State {
      final String data;
    
      StateData(this.data);
    }
    
    class StateError extends State {
      final dynamic error;
    
      StateError(this.error);
    }

you need to annotate the parent abstract class @likeSealed

and run command pub run build_runner build

Collection of constructor

name = {name of parent class}s = States

a class with a collection of inherited classes constructors

    class States {
        static StateData data(
         String data,
        ) {
          return StateData(data);
        }
        
        static StateError error(
         dynamic error,
        ) {
          return StateError(error);
        }
    }

Switch of sealed classes

name = {name of parent class}Switch = StateSwitch

a class with switch of inherited classes

    abstract class StateSwitch<T> implements SealedSwitch<State, T> {
        T switchCase(State type) => type is StateData
            ? onData(type)
            : type is StateError
                ? onError(type)
                : onDefault(type);
        T onData(StateData data);
        T onError(StateError error);
        T onDefault(State state) => throw UnimplementedError();
    }

see the example where the package is used with bloc

Libraries

like_sealed_gen