functional_enum

Last updated:

0 purchases

functional_enum Image
functional_enum Images
Add to Cart

Description:

functional enum

Functional Enum #
Freezed, but for enums.
Code generator for functional enum that makes the use of enums much better.
Installation #
Add the following dependencies to your project.
dependencies:
functional_enum_annotation:

dev_dependencies:
build_runner:
functional_enum:
copied to clipboard
Usage #
With pure dart
import 'package:functional_enum_annotation/functional_enum_annotation.dart';

// assuming your file name is main.dart
part 'main.g.dart';

@functionalEnum
enum Shape { square, circle, triangle }

void main() {
final shape = Shape.circle;

// all cases must be handled
final message = shape.when(
square: () => 'I am a Square',
circle: () => 'I am a Circle',
triangle: () => 'I am a Triangle',
);
print(message); // I am a Circle

// all cases may not be handled but `orElse` cannot be null
final canBeRotated = shape.maybeWhen(
circle: () => false,
orElse: () => true,
);
print(canBeRotated); // false

// equivalent to print(shape == Shape.circle)
print(shape.isCircle); // true
print(shape.isSquare); // false
print(shape.isTriangle); // false
}
copied to clipboard
With flutter
import 'package:functional_enum_annotation/functional_enum_annotation.dart';

// assuming your file name is main.dart
part 'main.g.dart';

@functionalEnum
enum AppState { initial, loading, loaded }

class MyWidget extends StatelessWidget {
final Appstate appState;

const MyWidget({Key key, this.appState}) : super(key: key);

@override
Widget build(BuildContext context) {
return appState.when(
initial: () => SizedBox(),
loading: () => CircularProgressIndicator(),
loaded: () => HomePage(),
);
}
}
copied to clipboard
Generate the code #
Once you have completed the above steps, you should run the build_runner to generate the code for you.
You can use the following commands to run the code generator:

For dart projects use

$ dart pub run build_runner build
copied to clipboard

and for flutter projects use

$ flutter pub run build_runner build
copied to clipboard
Maintainers #

Elias Andualem

License:

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Files In This Product:

Customer Reviews

There are no reviews.