Skip to content

vrtdev/sealed_class_generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sealed Class Generator

sealed_class: pub package
sealed_class_generator: pub package

Fix Dart's lack of a sealed class.
Inspired by Kotlin's implementation and by Sealed Unions.
With this lib you can generate an unlimited amount of sealed subclasses.

Installation

dependencies:
  sealed_class: 2.0.0

dev_dependencies:
  sealed_class_generator: 2.0.0
  build_runner: X.X.X

How to use:

A complete example is found in the example.

Define your Sealed class by annotating it with @Sealed()

part 'yourfilename.g.dart';

@Sealed()
abstract class Result{}

Add the subclasses to the annotation.

part 'yourfilename.g.dart';

@Sealed([Failure, Success])
abstract class Result{}

Your subclasses should implement your sealed class.

@Sealed([Failure, Success])
abstract class Result {}

class Failure implements Result {
  final String errorMessage;

  Failure(this.errorMessage);
}

class Success implements Result {
  final String data;

  Success(this.data);
}

The complete file should now look like this:

import 'package:sealed_class/sealed_class.dart';

part 'yourfilename.g.dart';

@Sealed([Failure, Success])
abstract class Result {}

class Failure implements Result {
  final String errorMessage;

  Failure(this.errorMessage);
}

class Success implements Result {
  final String data;

  Success(this.data);
}

To make it compile run the following command in the terminal:

flutter packages pub run build_runner build --delete-conflicting-outputs

You can do:

void main() {
  final someResult = Success("Woohoo Sealed classes in Dart");
  someResult.continued(
    (failure) {
      print("Oh no it failed with errorMessage: ${failure.errorMessage}");
    },
    (success) {
      print(success.data);
    },
  );

  //Or if you want to reduce it to another value use `join`
  final someOtherResult = Failure("Some Error Message");
  final mapResult = someOtherResult.join(
    (failure) => failure.errorMessage,
    (success) => success.data,
  );
  print(mapResult);
}

About

A poor mans sealed class generator for Dart

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published