Since Dart 2.17, we can declare enums with members. 🚀
Here's an example:
enum AuthException {
invalidEmail('Invalid email'),
emailAlreadyInUse('Email already in use'),
weakPassword('Password is too weak'),
wrongPassword('Wrong password');
const AuthException(this.message);
final String message;
}
const exception = AuthException.wrongPassword;
print(exception.message); // Wrong password
What else can you do with this?
- Define multiple properties
- Add named or positional arguments to the constructor (as long as it's a const constructor)
- Define custom methods and getters
Here's another example:
enum StatusCode {
badRequest(401, 'Bad request'),
unauthorized(401, 'Unauthorized'),
forbidden(403, 'Forbidden'),
notFound(404, 'Not found'),
internalServerError(500, 'Internal server error'),
notImplemented(501, 'Not implemented');
const StatusCode(this.code, this.description);
final int code;
final String description;
@override
String toString() => 'StatusCode($code, $description)';
}
This means that we no longer need a custom extension to "add" functionality to an enum, and this makes our code more clear and concise.
For more info about all the language features introduced by Dart 2.17, read the full announcement:
Happy coding!