
setState Isn't the Enemy: Ephemeral State vs App State in Flutter
- كاتب موثّق
- Flutter 3.x
محتويات المقال
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
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.
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
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."
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
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
Business logic inside a Stateclass is hard to test and reuse. That's an argument for moving logic out, not the checkbox.A setStatehigh 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 setStateafter anawait, when the widget is already gone, is an error.
Why the password leaked
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.
// 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, ), ), ); }}class PasswordField extends StatefulWidget { const PasswordField({super.key}); @override State<PasswordField> createState() => _PasswordFieldState();}class _PasswordFieldState extends State<PasswordField> { bool _visible = false; // ephemeral: only this field cares @override Widget build(BuildContext context) => TextField( obscureText: !_visible, decoration: InputDecoration( suffixIcon: IconButton( icon: Icon(_visible ? Icons.visibility_off : Icons.visibility), onPressed: () => setState(() => _visible = !_visible), ), ), );}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.
StatefulWidget and setState |
How to apply it in your project
Ask who needs the value If only one widget and its children read it, it's ephemeral. If another screen or feature needs it, it's app state. Keep ephemeral state in the widget Use a StatefulWidgetandsetState. Don't create a store, a provider and a state class for one widget'sbool.Promote state when the answer changes When 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. Move logic out, not the checkbox Pull business rules and I/O into plain Dart classes you can test without widgets, whichever way the UI state is held. Review scope, not the API In code review, ask "is this state in the right place?" instead of "is this setState?".
Key takeaways
setStateis Flutter's primitive for rebuilding a widget; libraries build on the same mechanism.Ephemeral state lives in one widget, and the docs say a StatefulWidgetis 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 setStatesmall and low in the tree, and never call it afterdispose.
التعليقات (0)