Bird
Raised Fist0
Fluttermobile~15 mins

setState for local state in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Counter Screen
A simple screen that shows a number and a button. When the button is pressed, the number increases by one using setState to update the UI.
Target UI
-------------------
|   Counter: 0    |
|                 |
|  [ Increment ]  |
-------------------
Display a number starting at 0
Add a button labeled 'Increment'
When the button is pressed, increase the number by 1
Use setState to update the displayed number
Starter Code
Flutter
import 'package:flutter/material.dart';

class CounterScreen extends StatefulWidget {
  @override
  State<CounterScreen> createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Counter: $_counter', style: TextStyle(fontSize: 24)),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // TODO: Add code to increment counter using setState
              },
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Solution
Flutter
import 'package:flutter/material.dart';

class CounterScreen extends StatefulWidget {
  @override
  State<CounterScreen> createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Counter: $_counter', style: TextStyle(fontSize: 24)),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _counter += 1;
                });
              },
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

This screen uses a StatefulWidget to hold a local integer state called _counter. The setState method is called inside the button's onPressed callback to tell Flutter that the state changed. Inside setState, we increase _counter by 1. Flutter then rebuilds the UI, showing the updated number. This is the basic way to update local state and refresh the UI in Flutter.

Final Result
Completed Screen
-------------------
|   Counter: 1    |
|                 |
|  [ Increment ]  |
-------------------
User taps the 'Increment' button
The number shown after 'Counter:' increases by 1 each tap
Stretch Goal
Add a 'Reset' button that sets the counter back to zero
💡 Hint
Add another ElevatedButton below the Increment button. In its onPressed, call setState and set _counter to 0.

Practice

(1/5)
1. What is the main purpose of calling setState() inside a StatefulWidget in Flutter?
easy
A. To navigate to a new screen
B. To permanently save data to the device
C. To initialize variables before the widget builds
D. To update the local state and refresh the UI

Solution

  1. Step 1: Understand the role of setState()

    setState() tells Flutter that the widget's state has changed and the UI should update.
  2. Step 2: Differentiate from other actions

    Navigation, initialization, and saving data are different tasks not handled by setState().
  3. Final Answer:

    To update the local state and refresh the UI -> Option D
  4. Quick Check:

    setState updates UI = B [OK]
Hint: Remember: setState refreshes UI after state changes [OK]
Common Mistakes:
  • Thinking setState navigates screens
  • Using setState to save data permanently
  • Confusing setState with widget initialization
2. Which of the following is the correct syntax to update a counter variable inside setState() in Flutter?
easy
A. setState(() { counter += 1; });
B. setState { counter = counter + 1; }
C. setState(() => counter = counter + 1);
D. setState(counter += 1);

Solution

  1. Step 1: Recall correct setState syntax

    The correct syntax uses a function with curly braces: setState(() { ... });
  2. Step 2: Check each option

    setState(() { counter += 1; }); uses the correct syntax with a function block. setState { counter = counter + 1; } misses parentheses. setState(() => counter = counter + 1); uses arrow syntax but must return void, so it's invalid here. setState(counter += 1); passes an expression directly, which is incorrect.
  3. Final Answer:

    setState(() { counter += 1; }); -> Option A
  4. Quick Check:

    setState needs a function block = A [OK]
Hint: Use setState(() { ... }) with braces for updates [OK]
Common Mistakes:
  • Omitting parentheses after setState
  • Using arrow function incorrectly inside setState
  • Passing expressions directly without a function
3. Consider this Flutter code snippet inside a StatefulWidget:
int count = 0;

void increment() {
  setState(() {
    count += 2;
  });
}

// Widget build shows count value
What will be the displayed count after calling increment() twice starting from 0?
medium
A. 4
B. 2
C. 1
D. 0

Solution

  1. Step 1: Understand the increment logic

    Each call to increment() adds 2 to count.
  2. Step 2: Calculate after two calls

    Starting at 0, after first call: 0 + 2 = 2; after second call: 2 + 2 = 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    2 increments x 2 each = 4 [OK]
Hint: Multiply increments by added value for quick result [OK]
Common Mistakes:
  • Adding only 1 instead of 2 per call
  • Forgetting to call setState to update UI
  • Assuming count resets after each call
4. What is wrong with this Flutter code inside a StatefulWidget?
int counter = 0;

void increment() {
  counter += 1;
}

// UI shows counter value
Why does the UI not update when increment() is called?
medium
A. Because increment() is missing a return type
B. Because counter is declared outside the widget
C. Because setState() is not called to notify Flutter of the change
D. Because counter should be final

Solution

  1. Step 1: Identify state update mechanism

    Flutter updates UI only when setState() is called to notify changes.
  2. Step 2: Analyze the code

    The code changes counter but does not call setState(), so UI does not refresh.
  3. Final Answer:

    Because setState() is not called to notify Flutter of the change -> Option C
  4. Quick Check:

    Missing setState means no UI update [OK]
Hint: Always wrap state changes inside setState() [OK]
Common Mistakes:
  • Updating variables without setState
  • Thinking return type affects UI update
  • Confusing variable scope with UI refresh
5. You have a counter app where pressing a button increases the count by 1. You want to add a feature: if the count is even, pressing the button adds 2 instead of 1. Which is the correct way to implement this using setState()?
hard
A. count = (count % 2 == 0) ? count + 2 : count + 1;
B. setState(() { count = (count % 2 == 0) ? count + 2 : count + 1; });
C. setState(() => count += (count % 2 == 0) ? 2 : 1);
D. if (count % 2 == 0) { count += 2; } else { count += 1; }

Solution

  1. Step 1: Ensure state changes are inside setState

    Only changes inside setState() trigger UI updates.
  2. Step 2: Check conditional logic placement

    setState(() { count = (count % 2 == 0) ? count + 2 : count + 1; }); correctly places the conditional update inside setState(). if (count % 2 == 0) { count += 2; } else { count += 1; } updates state outside setState, so UI won't refresh. setState(() => count += (count % 2 == 0) ? 2 : 1); uses arrow syntax but must return void, so it's invalid. count = (count % 2 == 0) ? count + 2 : count + 1; updates state without setState.
  3. Final Answer:

    setState(() { count = (count % 2 == 0) ? count + 2 : count + 1; }); -> Option B
  4. Quick Check:

    Conditional update inside setState = D [OK]
Hint: Put all state changes inside setState with conditions [OK]
Common Mistakes:
  • Updating state outside setState
  • Using arrow function for multiple statements
  • Forgetting to call setState entirely
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