Menu
CoddyTech

setState Redraws the Screen

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 11 of 34.

Press Add one in this app and watch the Console: 1, 2, 3. The number on the screen stays 0. Flutter built the screen once, and nothing told it to build again.

A StatelessWidget never changes. A screen that changes is a StatefulWidget, written as two classes:

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Text('$_count');
  }
}

HomePage only says which State to make (createState, written in the arrow form from Functions That Return Values). _HomePageState does the work: it keeps the screen's data in variables at its top, like _count, and builds the screen. It lives as long as the screen does, so _count keeps its value from one build to the next.

To change the screen, change the data inside setState. It tells Flutter "this changed, build again", and the Text shows the new number:

setState(() {
  _count = _count + 1;
});

The underscore at the start of _HomePageState and _count makes a name private: only this file can use it. State classes and their variables usually have one.

challenge icon

Challenge

Medium

Make the number on the screen go up by one on every press of Add one: put the change to _count inside setState.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('$_count', style: TextStyle(fontSize: 48)),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                _count = _count + 1;
                print(_count);
              },
              child: Text('Add one'),
            ),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler