Differentiate between ephemeral state and app state

This doc introduces app state, ephemeral state, and how you might manage each in a Flutter app.

In the broadest possible sense, the state of an app is everything that exists in memory when the app is running. This includes the app's assets, all the variables that the Flutter framework keeps about the UI, animation state, textures, fonts, and so on. While this broadest possible definition of state is valid, it's not very useful for architecting an app.

First, you don't even manage some state (like textures). The framework handles those for you. So a more useful definition of state is "whatever data you need in order to rebuild your UI at any moment in time". Second, the state that you do manage yourself can be separated into two conceptual types: ephemeral state and app state.

Ephemeral state

Ephemeral state (sometimes called UI state or local state) is the state you can neatly contain in a single widget.

This is, intentionally, a vague definition, so here are a few examples.

  • current page in a PageView
  • current progress of a complex animation
  • current selected tab in a BottomNavigationBar

Other parts of the widget tree seldom need to access this kind of state. There is no need to serialize it, and it doesn't change in complex ways.

In other words, there is no need to use state management techniques (ScopedModel, Redux, etc.) on this kind of state. All you need is a StatefulWidget.

Below, you see how the currently selected item in a bottom navigation bar is held in the _index field of the _MyHomepageState class. In this example, _index is ephemeral state.

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

  
  State<MyHomepage> createState() => _MyHomepageState();
}

class _MyHomepageState extends State<MyHomepage> {
  int _index = 0;

  
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: _index,
      onTap: (newIndex) {
        setState(() {
          _index = newIndex;
        });
      },
      // ... items ...
    );
  }
}
ON THIS PAGE