Is there a Performance impact if we just use StatefullWidget over the StatelessWidget it vice-versa?
In my point of view, we just use StatefullWidget
for things like update part of the UI using setState()
, have a way to setup some code in the initState()
and dispose things in the dispose()
function. So when I don't need those things I go ahead and use StatelessWidget
.
But what is the real performance impact between these two most used widgets?
Stateful and stateless widgets 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.
Stateless widget overrides the build() method and returns a widget. For example, we use Text or the Icon is our flutter application where the state of the widget does not change in the runtime. It is used when the UI depends on the information within the object itself.
Any application, architecture, server, or IT infrastructure resource that tracks information regarding its state, is known as a stateful resource. They are more reliable but may not be ideal for real-time performance, which must work without downtime. In that case, stateless would be the way to go.
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.
Performance-wise, a StatelessWidget
is almost identical to a StatefulWidget
with an empty State
.
Writing:
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
or:
class Example extends StatefulWidget {
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
@override
Widget build(BuildContext context) {
return Container();
}
}
won't have any visible impact on the performance of your app.
There indeed is a small gain when using StatelessWidget
here. But it's ridiculously small:
The difference between them can be summarized as calling an empty function vs not calling it. It's something, but absolutely doesn't matter.
The reason being, internally the implementation of StatefulWidget
and StatelessWidget
is almost the same.
StatelessWidget
does have all the extra life-cycles that StatefulWidget
possess.
It has an "initState"/"dispose". Even a setState
!
They are just not part of the public API.
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