Language 9 of 10 · Topic 0.5

Control Flow: Switch Expressions & Guard Clauses (Dart 3)

1Concept

Dart 3 switch expressions evaluate patterns and return values with arrow (=>) syntax and when guards.

2Architecture Diagram

var desc = status switch {
  Status.loading => 'Loading...',
  Status.success when data != null => 'Data: $data',
  _ => 'Unknown'
};

3Code Example

Stage 0 Language Foundations
enum AuthState { unauthenticated, authenticating, authenticated }

String getStatusMessage(AuthState state) => switch (state) {
  AuthState.unauthenticated => 'Please sign in.',
  AuthState.authenticating => 'Verifying credentials...',
  AuthState.authenticated => 'Welcome back!'
};

void main() {
  print(getStatusMessage(AuthState.authenticated));
}

4Expected Output

Welcome back!

5Key Takeaways

  • Switch expressions are exhaustive over enums and sealed classes.
  • Guard clauses (when) provide fine-grained conditions.
  • Arrow syntax eliminates break statements.