Flutter performance of StatefulWidget and StatelessWidget
Keeping it simple:
- If you have non-
final
global variables in your widget then you need aStatefulWidget
- If all global variables are
final
then you should useStatelessWidget
;
Reason:
- If your global variable is non final that means it is allowed to change and if it's value is changed that means state of your object(Widget) is changed (basic oops concept I am talking about). In such case you would like to call build method of your widget so that your changes get applied on the UI (if it matters for your UI). We do it by calling
setState();
and so we useStatefulWidget
for such use-case. - If it is enough that once you initialize your global variable in constructor, you don't need to assign it any value in future then in such case use
StatelessWidget
.
I have tried to keep it very simple and not technical enough so, if you still have any doubts please comment on this answer.
You use StatelessWidget
for widgets that don't change their state, that will stay the same all the time. Example, appBar
is stateless.. The build(...)
function of the StatelessWidget
is called only once and no amount of changes in any Variable(s)
, Value(s)
or Event(s)
can call it again.
Therefore, when you need to change state(ex value) then use StatefulWidgets
, basically StatelessWidget
is used for building UI widgets that are static
StatefulWidget
is necessary for when the widget itself is maintaining its own state. In the example you gave, the Provider
package is handling the state for you, assuming you're using the correct provider type higher up the widget tree (for example, ChangeNotifierProvider
). There also doesn't seem to be anything in this code that would benefit from having access to the widget's lifecycle, so you wouldn't need access to methods like initState
or dispose
.
As such, there's nothing for the widget itself to manage, so converting your class to be stateful is unnecessary.
One thing I might suggest, though, is to use a Consumer
instead of calling Provider.of
directly. A Consumer
handles the call for you and removes any ambiguity on whether your widget will get updated when the Provider
detects a state change.