DartIntermediate 2 min read

Dart switch expressions and guards: select a delivery fee

Match ordered cases and guards while keeping the result exhaustive and understandable.

On this page

Delivery pricing is a decision table. A switch expression can return one fee from that table without assigning a temporary variable in several branches. Keep the order intentional: the first matching case wins.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
int deliveryFee({required int totalPaise, required bool express}) =>
    switch ((totalPaise, express)) {
      (< 0, _) => throw ArgumentError('Total cannot be negative.'),
      (_, true) => 7000,
      (final total, false) when total >= 50000 => 0,
      _ => 2500,
    };

void main() {
  print(deliveryFee(totalPaise: 60000, express: false));
  print(deliveryFee(totalPaise: 60000, express: true));
}

Follow the data and control flow

The record pattern considers amount and delivery mode together. Invalid totals are rejected before the express branch. A guard adds a boolean condition after a successful structural match. The wildcard supplies the final ordinary-delivery case.

Exhaustiveness is especially useful with enums and sealed hierarchies because the analyzer can identify missing variants. A guarded case alone may not cover every value of a type; keep the complete decision space in view.

A mistake to avoid

Putting a broad wildcard before a narrow case can make later branches unreachable. Also resist compressing a complex policy into one enormous expression. Extract named predicates or a pricing service once the rule needs independent documentation and testing.

Practice and verification

Add a pickup option represented by an enum and write down the expected fee table. Test the exact free-delivery threshold and an invalid negative total. Explain whether express delivery should override a membership discount or compose with it.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.