Enums in 'switch' Statements
Part of the Logic & Flow section of Coddy's Dart journey — lesson 61 of 65.
One of the most powerful applications of enums is using them with switch statements. When you combine enums with switch statements, you create code that is both safer and more maintainable.
Here's how you can use an enum in a switch statement:
enum Status {
pending,
running,
completed
}
Status currentStatus = Status.pending;
switch (currentStatus) {
case Status.pending:
print('Task is waiting to start');
break;
case Status.running:
print('Task is currently in progress');
break;
case Status.completed:
print('Task has been finished');
break;
}The beauty of using enums with switch statements is that Dart can verify you've handled all possible enum values. If you forget to include a case for one of the enum values, Dart will warn you, helping prevent bugs in your code.
This approach is much safer than using strings or numbers in switch statements, where typos could cause unexpected behavior. With enums, you get compile-time checking that ensures your code handles every possible scenario.
Challenge
EasyCreate a program that manages a game character's state using enums and switch statements. Your task is to:
- Define an enum called
CharacterStatewith the following values:idle,walking,running,jumping, andattacking - Create a variable called
currentStateof typeCharacterStateand assign it the valueCharacterState.idle - Create a function called
getStateMessagethat takes aCharacterStateparameter and returns a string message based on the state using a switch statement: - For
CharacterState.idle: return"Character is standing still" - For
CharacterState.walking: return"Character is moving slowly" - For
CharacterState.running: return"Character is moving quickly" - For
CharacterState.jumping: return"Character is in the air" - For
CharacterState.attacking: return"Character is fighting" - Print the initial state message using the function with the exact format:
Initial state: Character is standing still - Change the
currentStatetoCharacterState.walking - Print the updated state message with the exact format:
Updated state: Character is moving slowly - Change the
currentStatetoCharacterState.attacking - Print the final state message with the exact format:
Final state: Character is fighting
Your program should demonstrate the proper use of enums with switch statements, showing how this combination provides type-safe state management. The switch statement must handle all enum values and return the appropriate message for each character state. Make sure to follow Dart naming conventions and use the exact string messages specified above.
Cheat sheet
Enums work well with switch statements for type-safe code:
enum Status {
pending,
running,
completed
}
Status currentStatus = Status.pending;
switch (currentStatus) {
case Status.pending:
print('Task is waiting to start');
break;
case Status.running:
print('Task is currently in progress');
break;
case Status.completed:
print('Task has been finished');
break;
}Dart verifies that all enum values are handled in the switch statement, preventing bugs and providing compile-time checking.
Try it yourself
import 'dart:io';
// TODO: Define your CharacterState enum here
// TODO: Create your getStateMessage function here
void main() {
// TODO: Write your code below
// Create currentState variable and assign it CharacterState.idle
// Print initial state message
// Change currentState to CharacterState.walking
// Print updated state message
// Change currentState to CharacterState.attacking
// Print final state message
}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