Control flow helps your app decide what to do next. It lets your app choose between options, repeat tasks, or pick actions based on conditions.
0
0
Control flow (if, for, while, switch) in Flutter
Introduction
Show a message only if a user is logged in.
Repeat a list of items to display them on the screen.
Keep asking for input until the user provides a valid answer.
Choose different screens to show based on user choices.
Syntax
Flutter
if (condition) { // code to run if condition is true } else if (anotherCondition) { // code if anotherCondition is true } else { // code if none above are true } for (var item in collection) { // code to run for each item } while (condition) { // code to repeat while condition is true } switch (variable) { case value1: // code for value1 break; case value2: // code for value2 break; default: // code if no case matches break; }
if checks conditions and runs code accordingly.
for repeats code for each item in a list.
while repeats code while a condition stays true.
switch picks code to run based on a variable's value.
Examples
Checks if age is 18 or more, then prints 'Adult', otherwise 'Child'.
Flutter
if (age >= 18) { print('Adult'); } else { print('Child'); }
Prints 'Number 0', 'Number 1', and 'Number 2' one by one.
Flutter
for (var i = 0; i < 3; i++) { print('Number $i'); }
Repeats printing count until it reaches 3.
Flutter
int count = 0; while (count < 3) { print('Count is $count'); count++; }
Prints 'Stop' because color is 'red'.
Flutter
var color = 'red'; switch (color) { case 'red': print('Stop'); break; case 'green': print('Go'); break; default: print('Wait'); break; }
Sample App
This app shows a greeting based on the current time. It uses if and else if to pick the right greeting.
Flutter
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { int hour = DateTime.now().hour; String greeting; if (hour < 12) { greeting = 'Good morning!'; } else if (hour < 18) { greeting = 'Good afternoon!'; } else { greeting = 'Good evening!'; } return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Control Flow Example')), body: Center( child: Text( greeting, style: const TextStyle(fontSize: 24), ), ), ), ); } }
OutputSuccess
Important Notes
Always make sure your while loops have a way to stop, or your app may freeze.
Use break; in switch cases to stop checking further cases.
Indent your code inside control flow blocks to keep it clear and easy to read.
Summary
Control flow lets your app make decisions and repeat tasks.
if, for, while, and switch are common ways to control flow.
Use them to create interactive and dynamic apps.