How to Use Enhanced Enums with Members in Dart 2.17

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!

Want More?

Invest in yourself with my high-quality Flutter courses.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

The Complete Flutter Course Bundle

The Complete Flutter Course Bundle

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a full-stack Flutter eCommerce app on iOS, Android, and web.

Flutter Animations Masterclass - Full Course

Flutter Animations Masterclass - Full Course

Master Flutter animations and build a completely custom habit tracking application.