On this page12 sections
Lecture 047: Enums
| Day | Extra Topics |
| Lecture | 047 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
The days of the week, the status of an order, the size of a coffee: each has a fixed list of choices. An enum (short for enumeration) names those choices, so a typo like
'shiped'can never sneak into your program.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lecture 019 (switch) and lectures 030–031 (classes and constructors).
Learning Objectives
- Declare an enum and use its values
- Read an enum value's
nameandindex - Loop over all values with
values - Use an enum in a
switch, and let Dart check that every case is covered - Give enum values their own data (enhanced enums)
1. Why Not Just Strings?
var status = 'shiped'; // typo: nobody notices until something breaksWith an enum, only the real choices exist, and a typo is a compile error.
2. Declaring and Using an Enum
enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
void main() {
var today = Day.friday;
print(today); // Day.friday
print(today.name); // friday
print(today.index); // 4 (counting starts at 0)
print(Day.values.length); // 7
print(Day.values.first); // Day.monday
}| Property | Gives |
|---|---|
value.name | the name as a String ('friday') |
value.index | its position, starting at 0 |
EnumName.values | a list of every value, in order |
EnumName.values.byName('x') | the value called 'x' |
3. Looping Over All Values
enum OrderStatus { pending, shipped, delivered, cancelled }
for (var s in OrderStatus.values) {
print('${s.index}: ${s.name}');
}Output
0: pending
1: shipped
2: delivered
3: cancelled4. Enums and switch
var status = OrderStatus.shipped;
switch (status) {
case OrderStatus.pending:
print('Waiting to be packed');
case OrderStatus.shipped:
print('On the way');
case OrderStatus.delivered:
print('Enjoy!');
case OrderStatus.cancelled:
print('Order cancelled');
}Output: On the way
Dart checks that you handled every value. Add a new status later and forget it, and Dart
points to the switch that needs updating.
5. Enums With Data (Enhanced Enums)
Each value can carry its own fields, and the enum can have methods:
enum Planet {
mercury(3.7),
earth(9.8),
jupiter(24.8);
final double gravity;
const Planet(this.gravity);
double weightOf(double massKg) => massKg * gravity;
}
print(Planet.jupiter.gravity); // 24.8
print(Planet.earth.weightOf(60).toStringAsFixed(1)); // 588.0The values end with ; when more code follows, the fields must be final, and the constructor
must be const.
Code Examples
Example 1: A Drinks Menu
enum Size {
small(250, 150),
medium(350, 200),
large(500, 260);
final int ml;
final int price;
const Size(this.ml, this.price);
}
enum Drink { tea, coffee, juice }
void main() {
var drink = Drink.coffee;
var size = Size.large;
print('Order: ${size.name} ${drink.name}');
print('Amount: ${size.ml} ml');
print('Price: Rs ${size.price}');
print('--- Menu ---');
for (var s in Size.values) {
print('${s.name.padRight(7)} ${s.ml} ml Rs ${s.price}');
}
}Output
Order: large coffee
Amount: 500 ml
Price: Rs 260
--- Menu ---
small 250 ml Rs 150
medium 350 ml Rs 200
large 500 ml Rs 260padRight(7) adds spaces so the columns line up.
Common Beginner Mistakes
1. Missing a case in a switch
enum Light { red, yellow, green }
switch (light) {
case Light.red:
print('Stop');
case Light.green:
print('Go');
}Error: The type 'Light' is not exhaustively matched by the switch cases since it doesn't match 'Light.yellow'.
Try adding a default case or cases that match 'Light.yellow'.2. Assigning a string to an enum variable
Light light = 'red';Error: A value of type 'String' can't be assigned to a variable of type 'Light'.Write Light.red, or convert text with Light.values.byName('red').
3. Saving index and reordering later: if you store index (say, in a database) and then
insert a new value in the middle, every saved number shifts. Store name instead.
4. Forgetting ; before fields in an enhanced enum: the list of values must end with ;
when fields or methods follow.
Practice Questions
- Declare an enum
Seasonwith four seasons. - What does
Season.values.lengthgive? - What is
Season.summer.name? - Why is
OrderStatus.shippedsafer than the string'shipped'? - What happens if a
switchoverSeasonhandles only three seasons and has nodefault?
Practice Answers
enum Season { spring, summer, autumn, winter }4'summer'- A typo in an enum value is a compile error; a typo in a string goes unnoticed.
- Dart reports a compile error: the switch isn't exhaustive.
Key Takeaways
- An enum is a fixed set of named values:
enum Day { monday, ... }. - Use
.name,.index,.valuesand.values.byName(). - A
switchon an enum must cover every value; Dart checks. - Enhanced enums give each value its own data and methods.
- Prefer enums over magic strings for fixed choices.