Dart Control Flow and Functions

Google Flutter 12 min min read Updated: Nov 16, 2026 Beginner
Dart Control Flow and Functions
Beginner Topic 2 of 8

Making Decisions: if and else

dart int score = 72; if (score >= 90) { print('Grade A'); } else if (score >= 60) { print('Grade B'); } else { print('Try again'); } // Short form with the ternary operator String result = score >= 40 ? 'Pass' : 'Fail';

Loops

dart for (int i = 1; i <= 3; i++) { print('Round $i'); } var fruits = ['apple', 'banana', 'mango']; for (final fruit in fruits) { print(fruit); } int n = 3; while (n > 0) { print(n); n--; }

Use break to leave a loop early and continue to skip to the next turn.

switch

dart String day = 'Sat'; switch (day) { case 'Sat': case 'Sun': print('Weekend'); default: print('Weekday'); } // Dart 3 switch expression: returns a value var kind = switch (day) { 'Sat' || 'Sun' => 'Weekend', _ => 'Weekday', };

Functions

dart int add(int a, int b) { return a + b; } // Arrow function: one expression int multiply(int a, int b) => a * b; void main() { print(add(2, 3)); // 5 print(multiply(2, 3)); // 6 }

Optional and Named Parameters

Flutter uses named parameters everywhere, so this part is very important.

dart // Optional positional: in square brackets String greet(String name, [String greeting = 'Hello']) { return '$greeting, $name!'; } // Named: in curly braces void showUser({required String name, int age = 18, String? city}) { print('$name, $age, ${city ?? 'unknown'}'); } void main() { print(greet('Asha')); // Hello, Asha! print(greet('Asha', 'Hi')); // Hi, Asha! showUser(name: 'Ravi', city: 'Pune'); // order does not matter }
StyleSyntaxCall
Positionalf(int a, int b)f(1, 2)
Optional positionalf(int a, [int b = 0])f(1)
Namedf({int a = 0})f(a: 1)
Required namedf({required int a})f(a: 1) (must be given)
Where you will see this: Text('Hi', style: ..., textAlign: ...). Everything after the first argument is a named parameter.

Functions as Values

dart var numbers = [1, 2, 3, 4]; var doubled = numbers.map((n) => n * 2).toList(); // [2, 4, 6, 8] var evens = numbers.where((n) => n.isEven).toList(); // [2, 4] // Pass a function to another function void run(void Function() action) => action(); run(() => print('Hi!'));

Short functions without a name, written as (args) => result, are called lambdas or closures. You will use them for button callbacks such as onPressed: () { ... }.

Conclusion

Control flow and functions are the building blocks of every program. Remember named parameters and required, because every widget uses them.

Quick Summary: Use if, for, while and switch. Functions can have positional, optional and named parameters, and can be passed around as values.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators