StatelessWidget and StatefulWidget
Preface
In Flutter development, you can say that “everything is a widget”. Common terms in frontend frameworks like View, View Controller, Activity, Application, Layout, etc. are all widgets in Flutter.
Widgets in Flutter come in two types: StatelessWidget and StatefulWidget. The difference between them is:
- StatefulWidget handles scenarios with interaction or visual changes;
- StatelessWidget handles static scenarios that do not change;
StatelessWidget
- When to use it: if all the parameters you need are available at the start of rendering, you can use StatelessWidget directly. In other words, when a widget no longer needs to care about or respond to data changes after it has been built, use StatelessWidget.
StatefulWidget
- A widget with state
- Use
setState((){})to update data and trigger build(), re-rendering the widget - Lifecycle (so far in my projects, the most commonly used ones are initState and dispose)
- initState: called only once during the entire lifecycle, can be used to initialize some data
- didChangeDependencies: specifically handles changes in the State’s dependencies
- build: returns a widget that is the UI of this screen
- didUpdateWidget(Widget oldWidget): triggered whenever the parent widget calls
setState - deactivate: called when the visibility state of this widget changes; by definition it is called before
dispose, that is, before the widget is destroyed. (I haven’t run into this use case yet, will look into it more.) - dispose: called when the widget is permanently removed from the widget tree, usually used for “removing listeners”
Why do we need StatelessWidget if StatefulWidget exists?
Even though StatefulWidget can handle every scenario, when setState is called to update the view, every child widget under that StatefulWidget will also be rebuilt, which represents huge resource consumption and a serious hit to Flutter’s rendering performance.
Imagine the root layout of a page is a StatefulWidget; every UI update inside its State means the entire page’s widgets are destroyed and rebuilt.
So use it carefully!!
ChangeLog
- 20260501–translate by claude code