I have noticed that, we can use a StatefulWidget
to build any part of the UI without worrying about the state.
What I am asking is simply, what are the reasons behind having a StatelessWidget
in the first place, when we can build any UI class as a StatefulWidget
whether we are going to provide it with a State
or not?
Does using a StatefulWidget
comes with an additional cost that makes creating a stateless UI easier/faster/better using a StatelessWidget
?
When I read the docs, I can not exactly point out the difference between using StatelessWidget
and StatefulWidget
when describing stateless UI components. It is even recommended to
Consider refactoring the stateless widget into a stateful widget so that it can use some of the techniques described at StatefulWidget...
The name of the stateless widget is MyApp which is being called from the runApp() and extends a stateless widget. Inside this MyApp a build function is overridden and takes BuildContext as a parameter. This BuildContext is unique to each and every widget as it is used to locate the widget inside the widget tree.
A widget is either stateful or stateless. If a widget can change—when a user interacts with it, for example—it's stateful. A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets.
build method Null safetyDescribes the part of the user interface represented by this widget. The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes).
Stateful widgets are useful when the part of the user interface you are describing can change dynamically, e.g. due to having an internal clock-driven state, or depending on some system state.
If your widget manages state, you should use a StatefulWidget
with an associated State
object to store the state.
If your widget doesn't manage any state, and its build method only depends on its constructor arguments (or Inherited
widgets such as Theme
), it's better to use a StatelessWidget
. StatelessWidget
requires defining fewer classes and invoking fewer methods, so it should be faster and more maintainable than an equivalent StatefulWidget
that doesn't cache anything in its state.
If you follow the Push the state to the leaves performance optimization, you will be changing a StatefulWidget
to a StatelessWidget
and factoring out the stateful parts into a simpler StatefulWidget
(which may take a child
argument and cache it). This pattern adds more classes but has the benefit of reducing the amount of work necessary when the state changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With