What are Enums?
Part of the Logic & Flow section of Coddy's Dart journey — lesson 58 of 65.
When writing programs, you often need to represent a fixed set of related values. For example, the days of the week, different weather conditions, or the status of a task. Instead of using strings like "Monday", "Tuesday" or integers like 1, 2, Dart provides a better solution called Enumerations or Enums.
An enum is a special data type that defines a collection of named constant values. Think of it as creating your own custom type with a limited set of possible values that never change.
enum Day {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}Using enums makes your code more readable and safer. Instead of remembering that 1 means Monday and 2 means Tuesday, you can use Day.monday and Day.tuesday. This prevents typos and makes your intentions clear to anyone reading your code.
Enums are particularly useful when you have a variable that can only hold one of several predefined values, making your programs more reliable and easier to understand.
Cheat sheet
An enum is a special data type that defines a collection of named constant values:
enum Day {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}Access enum values using dot notation: Day.monday, Day.tuesday
Enums make code more readable and safer by providing predefined constant values instead of using strings or integers.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List6Basic Error Handling
What are Exceptions?The 'try-catch' BlockCatching Exceptions with 'on'The 'finally' BlockThrowing an ExceptionRecap - Safe Division9Enumerations (Enums)
What are Enums?Defining a Simple EnumUsing Enums in VariablesEnums in 'switch' StatementsRecap - Traffic Light