DART / CHAPTER 02

Functions and control flow

Beginner

Build reusable calculations with explicit branches and parameters.

By the end of this chapter

  • Define typed function parameters
  • Use named optional parameters
  • Trace loop boundaries

The idea

A Dart function declares its parameters and can declare the type of its returned value. Required positional parameters express essential input, while named parameters make optional choices readable at the call site. A default value defines what happens when an optional argument is omitted. Keep a calculation’s return value separate from display code so the function can be tested and reused.

if statements require boolean conditions. for and while loops repeat work until their condition fails, so every loop needs a clear progress step. A for-in loop is convenient when values matter more than indices. Trace only the iterations that actually occur, and test empty input instead of assuming the body will run at least once.

Dart example
int countAtLeast(List<int> values, {int minimum = 0}) {
  var count = 0;
  for (final value in values) {
    if (value >= minimum) count++;
  }
  return count;
}
void main() { print(countAtLeast([1, 4, 2, 7], minimum: 4)); }
Result
2

The named argument changes the threshold to four. Values four and seven qualify, and the function returns their count rather than printing internally.

Try it yourself

Write a function that sums positive values and optionally doubles the final total with a named flag.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
var total = 0;
for (var i = 0; i < 5; i += 2) { total += i; }
print(total);