Menu
CoddyTech

Hot Reload Keeps State

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

The preview has two ways to bring in your changes. Run starts the app from scratch. Hot reload swaps in your new code while the app keeps running, and keeps the State: the counter keeps its number.

Try it: press plus a few times, change the number's color, and press Hot reload. The new color shows, and the count is still there. While you style a screen, that saves you from tapping your way back to where you were.

Hot reload builds the screen again with your new code, but it does not make a new State. So a change to a starting value, like int _count = 0; to int _count = 10;, does not show: that line only runs when the State is made. Press Run to see it.

The same goes for main, and for turning a StatelessWidget into a StatefulWidget. When a change does not show after Hot reload, press Run.

challenge icon

Challenge

Easy
  • Make the number size 64 and Colors.deepPurple. Press plus a few times first, then use Hot reload and see the count stay.
  • Make the counter start at 10. Notice that Hot reload does not show it, and Run does.

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;

  void _increase() {
    setState(() {
      _count++;
    });
  }

  void _decrease() {
    setState(() {
      _count--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Center(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(icon: Icon(Icons.remove), onPressed: _decrease),
            Text('$_count', style: TextStyle(fontSize: 48)),
            IconButton(icon: Icon(Icons.add), onPressed: _increase),
          ],
        ),
      ),
    );
  }
}
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