الانتقال إلى المحتوى
تطبيقات الموبايلState Management· 7 دقائق للقراءة

setState Isn't the Enemy: Ephemeral State vs App State in Flutter

State that lives in one widget belongs in that widget. Reach for a library when state is shared, not by default.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

A code review comment says "No setState in this codebase, please move it to a Cubit," and it's about the eye icon that shows or hides a password. The developer complies: a PasswordVisibilityCubit, provided once above MaterialApp, read by the password field. A week later a tester reports something odd. They reveal their password on the login screen, tap "Create account", and the sign-up form's password field is already showing its text.

The common misconception

The belief: setState is a beginner anti-pattern. Real apps put every piece of state in a state management library, and a StatefulWidget in a pull request is a sign that someone took a shortcut.

It's easy to see why people believe it. Tutorials start with setState and then "graduate" to Provider or Bloc, so it reads like training wheels. Many teams have been burned by the real problems: a 2,000-line StatefulWidget that mixes HTTP calls with UI, or a setState at the top of a screen that rebuilds everything. And "never use setState" is a rule that's easy to enforce in review. The half-truth: setState is the wrong tool for state that the whole app shares. For state that belongs to one widget, it's the right one.

What actually happens

Two kinds of state

The Flutter docs draw the line. , also called UI state or local state, "is the state you can neatly contain in a single widget": the current page of a PageView, the progress of an animation, the selected tab. Other parts of the tree seldom need it, you don't serialize it, and it doesn't change in complex ways, so "there is no need to use state management techniques" on it. "All you need is a StatefulWidget."

is the rest: state you share across many parts of the app and keep between sessions, such as login info, user preferences, notifications or a shopping cart. That's where a library earns its place.

The docs are honest that the line moves. You can even manage all of an app's state with setState, they note, as the starter app from flutter create does. The selected tab can become app state if other code must change it or it must survive a restart, and state that started ephemeral may need to move as the app grows. They quote Redux's author, Dan Abramov, for the rule of thumb: "Do whatever is less awkward."

setState is the primitive, not the toy

According to its API docs, setState's implementation is trivial: it calls your callback synchronously, then calls Element.markNeedsBuild. That's the same door the packages end up using. Flutter's options page describes InheritedWidget as "what package:provider and many other approaches use under the hood", and in flutter_bloc's source, BlocBuilder keeps its own State and calls setState when a new state arrives. A library adds structure, sharing and testability around that mechanism. It doesn't replace it.

The real problems behind the myth

The pain is real, but it comes from where state lives and what else lives with it:

  • Business logic inside a State class is hard to test and reuse. That's an argument for moving logic out, not the checkbox.
  • A setState high in the tree can rebuild the whole subtree below it. The API docs call that indirect cost "high".
  • State that two screens need, passed around through constructors and callbacks, is app state wearing the wrong clothes.
  • A setState after an await, when the widget is already gone, is an error.

None of these is fixed by moving a toggle into a global store.

Why the password leaked

The Bloc docs describe BlocProvider as a way to provide "a single instance of a bloc" to multiple widgets within a subtree. Provided above MaterialApp, that subtree is the whole app, so the login field and the sign-up field read the same bool. The state's scope became the provider's scope.

Dart password_field.dart
// Provided once above MaterialApp, so every screen shares itclass PasswordVisibilityCubit extends Cubit<bool> {  PasswordVisibilityCubit() : super(false);  void toggle() => emit(!state);}class PasswordField extends StatelessWidget {  const PasswordField({super.key});  @override  Widget build(BuildContext context) {    final visible = context.watch<PasswordVisibilityCubit>().state;    return TextField(      obscureText: !visible,      decoration: InputDecoration(        suffixIcon: IconButton(          icon: Icon(visible ? Icons.visibility_off : Icons.visibility),          onPressed: context.read<PasswordVisibilityCubit>().toggle,        ),      ),    );  }}

In a widget test that tapped the eye icon on one screen and then pushed a second screen with another password field, the Cubit version opened the second field with obscureText already false: the password was visible. The setState version opened it hidden, because each field has its own State. The second version is also shorter, and there's nothing to provide, close or reset.

Ephemeral stateApp state
ExamplesSelected tab, password visibility, an expanded tileLogged-in user, cart, preferences, unread counts
Who reads itOne widget, maybe its childrenSeveral screens or features
LifetimeAs long as the widgetAcross screens, often across sessions
Natural toolStatefulWidget and setStateA shared object and the approach your team picked

How to apply it in your project

  1. Ask who needs the valueIf only one widget and its children read it, it's ephemeral. If another screen or feature needs it, it's app state.
  2. Keep ephemeral state in the widgetUse a StatefulWidget and setState. Don't create a store, a provider and a state class for one widget's bool.
  3. Promote state when the answer changesWhen a second screen needs the value, or it must survive a restart, move it to app state with the approach your team uses. The docs expect this kind of refactor as an app grows.
  4. Move logic out, not the checkboxPull business rules and I/O into plain Dart classes you can test without widgets, whichever way the UI state is held.
  5. Review scope, not the APIIn code review, ask "is this state in the right place?" instead of "is this setState?".

Key takeaways

  • setState is Flutter's primitive for rebuilding a widget; libraries build on the same mechanism.
  • Ephemeral state lives in one widget, and the docs say a StatefulWidget is all it needs.
  • App state is shared across the app and often kept between sessions; that's where a library helps.
  • Lifting local state into a global store makes it shared, sometimes by accident.
  • Keep setState small and low in the tree, and never call it after dispose.

📚 المصادر

  1. Differentiate between ephemeral state and app state — Flutter docs
  2. Approaches to state management — Flutter docs
  3. State.setState — Flutter API
  4. Flutter Bloc Concepts — Bloc library

التعليقات (0)