Bird
Raised Fist0
Fluttermobile~20 mins

Control flow (if, for, while, switch) in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Control Flow Demo
This screen demonstrates basic control flow statements in Flutter: if, for, while, and switch. It shows a list of numbers and their classification using these statements.
Target UI
-------------------------
| Control Flow Demo     |
|-----------------------|
| Numbers:              |
| 1 2 3 4 5             |
|                       |
| Even or Odd:          |
| 1: Odd                |
| 2: Even               |
| 3: Odd                |
| 4: Even               |
| 5: Odd                |
|                       |
| Count Down:           |
| 5 4 3 2 1             |
|                       |
| Switch Example:       |
| Number 3 is Three     |
-------------------------
Display a list of numbers from 1 to 5 using a for loop.
For each number, show if it is Even or Odd using an if statement.
Show a countdown from 5 to 1 using a while loop.
Use a switch statement to display a message for number 3.
Starter Code
Flutter
import 'package:flutter/material.dart';

class ControlFlowDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Control Flow Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('Numbers:'),
            // TODO: Add code to display numbers 1 to 5 using for loop
            const SizedBox(height: 16),
            const Text('Even or Odd:'),
            // TODO: Add code to display if each number is even or odd using if
            const SizedBox(height: 16),
            const Text('Count Down:'),
            // TODO: Add code to display countdown from 5 to 1 using while loop
            const SizedBox(height: 16),
            const Text('Switch Example:'),
            // TODO: Add code to display message for number 3 using switch
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';

class ControlFlowDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<int> numbers = [];
    for (int i = 1; i <= 5; i++) {
      numbers.add(i);
    }

    List<String> evenOdd = [];
    for (var number in numbers) {
      if (number % 2 == 0) {
        evenOdd.add('$number: Even');
      } else {
        evenOdd.add('$number: Odd');
      }
    }

    List<int> countdown = [];
    int count = 5;
    while (count > 0) {
      countdown.add(count);
      count--;
    }

    String switchMessage;
    switch (3) {
      case 1:
        switchMessage = 'Number 3 is One';
        break;
      case 2:
        switchMessage = 'Number 3 is Two';
        break;
      case 3:
        switchMessage = 'Number 3 is Three';
        break;
      default:
        switchMessage = 'Number 3 is Unknown';
    }

    return Scaffold(
      appBar: AppBar(title: const Text('Control Flow Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('Numbers:'),
            Row(
              children: numbers
                  .map((n) => Padding(
                        padding: const EdgeInsets.only(right: 8.0),
                        child: Text('$n'),
                      ))
                  .toList(),
            ),
            const SizedBox(height: 16),
            const Text('Even or Odd:'),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: evenOdd
                  .map((text) => Text(text))
                  .toList(),
            ),
            const SizedBox(height: 16),
            const Text('Count Down:'),
            Row(
              children: countdown
                  .map((n) => Padding(
                        padding: const EdgeInsets.only(right: 8.0),
                        child: Text('$n'),
                      ))
                  .toList(),
            ),
            const SizedBox(height: 16),
            const Text('Switch Example:'),
            Text(switchMessage),
          ],
        ),
      ),
    );
  }
}

This Flutter widget shows how to use basic control flow statements.

  • For loop: We create a list of numbers from 1 to 5 and display them in a row.
  • If statement: We check each number to see if it is even or odd and display the result.
  • While loop: We count down from 5 to 1 and show the numbers in a row.
  • Switch statement: We check the number 3 and display a message accordingly.

This example helps beginners see how these control flows work in a simple Flutter UI.

Final Result
Completed Screen
-------------------------
| Control Flow Demo     |
|-----------------------|
| Numbers:              |
| 1 2 3 4 5             |
|                       |
| Even or Odd:          |
| 1: Odd                |
| 2: Even               |
| 3: Odd                |
| 4: Even               |
| 5: Odd                |
|                       |
| Count Down:           |
| 5 4 3 2 1             |
|                       |
| Switch Example:       |
| Number 3 is Three     |
-------------------------
The screen is static and shows the lists and messages.
No buttons or gestures are needed for this demo.
Stretch Goal
Add a button that when pressed, changes the number in the switch statement and updates the message accordingly.
💡 Hint
Use a StatefulWidget and setState to update the number and switch message.

Practice

(1/5)
1. Which control flow statement in Flutter is used to make decisions based on conditions?
easy
A. if
B. for
C. while
D. switch

Solution

  1. Step 1: Understand the purpose of control flow statements

    if statements let the app choose between actions based on conditions.
  2. Step 2: Identify the decision-making statement

    Among the options, only if directly tests a condition to decide what code runs.
  3. Final Answer:

    if -> Option A
  4. Quick Check:

    Decision making = if [OK]
Hint: Use if to check conditions and decide [OK]
Common Mistakes:
  • Confusing for loops with decision making
  • Thinking while is for choices instead of repetition
  • Assuming switch is the only decision tool
2. Which of the following is the correct syntax for a for loop in Flutter to print numbers 0 to 4?
easy
A. for (int i = 1; i < 5; i++) { print(i); }
B. for i in 0 to 4 { print(i); }
C. for (int i = 0; i < 5; i++) { print(i); }
D. for (i = 0; i <= 5; i++) print(i);

Solution

  1. Step 1: Check the loop initialization and condition

    for (int i = 0; i < 5; i++) { print(i); } initializes i at 0 and loops while i < 5, which prints 0 to 4.
  2. Step 2: Verify syntax correctness

    for (int i = 0; i < 5; i++) { print(i); } uses correct Dart syntax with types and braces.
  3. Final Answer:

    for (int i = 0; i < 5; i++) { print(i); } -> Option C
  4. Quick Check:

    Correct Dart for loop syntax = for (int i = 0; i < 5; i++) { print(i); } [OK]
Hint: Remember Dart for loops use semicolons and braces [OK]
Common Mistakes:
  • Using Python-style loops like 'for i in 0 to 4'
  • Off-by-one errors in loop conditions
  • Missing type declaration for loop variable
3. What will be the output of this Flutter Dart code?
int count = 0;
while (count < 3) {
  print(count);
  count++;
}
medium
A. 1 2 3
B. No output
C. 0 1 2 3
D. 0 1 2

Solution

  1. Step 1: Analyze the while loop condition and increments

    The loop starts with count = 0 and runs while count < 3, printing count each time.
  2. Step 2: Trace the printed values

    It prints 0, then increments to 1, prints 1, increments to 2, prints 2, increments to 3, then stops.
  3. Final Answer:

    0 1 2 -> Option D
  4. Quick Check:

    Loop prints values less than 3 = 0 1 2 [OK]
Hint: Count starts at 0 and stops before 3, so prints 0,1,2 [OK]
Common Mistakes:
  • Including 3 in output mistakenly
  • Confusing post-increment behavior
  • Thinking loop runs zero times
4. Identify the error in this Flutter Dart code snippet:
int i = 0;
while (i < 5) {
  print(i);
}
medium
A. Missing increment of i inside the loop
B. Incorrect while loop syntax
C. Variable i should be declared inside the loop
D. print() cannot be used inside loops

Solution

  1. Step 1: Check loop control variables

    The variable i is initialized but never changed inside the loop.
  2. Step 2: Understand loop behavior

    Without incrementing i, the condition i < 5 is always true, causing an infinite loop.
  3. Final Answer:

    Missing increment of i inside the loop -> Option A
  4. Quick Check:

    Loops need changing variables to stop [OK]
Hint: Always update loop variables to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting to increment loop counters
  • Assuming loop ends automatically
  • Misunderstanding while loop syntax
5. You want to display a message in Flutter based on a user's score:
int score = 75;
switch (score ~/ 10) {
  case 10:
  case 9:
    print('Excellent');
    break;
  case 8:
    print('Very Good');
    break;
  case 7:
    print('Good');
    break;
  default:
    print('Keep Trying');
}

What message will be printed?
hard
A. Excellent
B. Good
C. Very Good
D. Keep Trying

Solution

  1. Step 1: Calculate the switch expression value

    score is 75, so score ~/ 10 is integer division 75/10 = 7.
  2. Step 2: Match the case for value 7

    Case 7 matches and prints 'Good'.
  3. Final Answer:

    Good -> Option B
  4. Quick Check:

    Integer division selects case 7 = 'Good' [OK]
Hint: Use integer division to group scores in switch cases [OK]
Common Mistakes:
  • Forgetting integer division operator ~/
  • Assuming score matches case directly
  • Missing break statements causing fall-through
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard