DartBasic 2 min read

Dart if, switch and loops: process an order queue

Choose branches, iterate with for and while, and use break and continue intentionally.

On this page

An operations dashboard often processes a queue with simple rules. Start with a plain loop so the order of decisions is visible before replacing it with collection transformations. A good loop has a clear stopping condition and a predictable effect.

Worked example

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

main.dart
void main() {
  final quantities = [2, 0, 4, -1, 3];
  var processed = 0;
  for (final quantity in quantities) {
    if (quantity < 0) {
      print('Invalid quantity; stop for review.');
      break;
    }
    if (quantity == 0) continue;
    processed += quantity;
  }
  final label = switch (processed) {
    0 => 'No items',
    <= 5 => 'Small batch',
    _ => 'Large batch',
  };
  print('$processed items: $label');
}

Follow the data and control flow

The first and third entries contribute six items. continue skips the zero entry; break stops at the invalid quantity, so the final three is never processed. The switch expression maps the resulting count to one label and uses a wildcard for the remaining cases.

Use for-in when the value is what matters. An indexed loop is useful when the index itself has meaning. A while loop suits a condition-driven process, but make sure its body can change that condition. A switch expression returns a value; a switch statement can contain multiple actions.

A mistake to avoid

Replacing break with continue changes the business rule from stopping a batch to ignoring an invalid record. Neither is automatically correct. Also avoid changing a collection’s length while iterating over it; collect edits separately when mutation would invalidate traversal.

Practice and verification

Predict the result after replacing break with continue. Rewrite the example with a while loop and demonstrate that it terminates. Add one explicit branch for an exactly six-item batch without creating overlapping unreachable cases.

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.