Stateful widget is that which maintains State and responds/rebuilds (itself) when there are any changes in the state.
Where as Stateless widget does not have a state. It is static and cannot rebuild.
In simple words - Stateful widgets are mutable & Stateless widgets are immutable
lets go through some code
We are going to have 'Text' widget and 'TextField' widget to see the difference between Stateful and Stateless widget.
The above snippet is the syntax/signature for the stateless widget.
It has 'class' which 'extends StatelessWidget'
'build' override method is responsible to draw the UI.
We are having a field called 'textValue' which was given to 'Text' widget and the same field was changed by handing 'onChanged' in 'TextField' widget.
But the changes in TextField was not reflecting in the Text widget. Means the state of 'textValue' is immutable
Let us take the same scenario in Stateful widget.
The above snippet is the syntax/signature for the stateful widget.
It has 'class' which 'extends StatefulWidget'
Stateful widget will overrides a createState to get the state for the widget.
Now it is State's responsibility to update the UI. Yes you guessed it.
build method will be available in State & not in the widget itself.
This time everything is same but with a little change in onChanged text field callback, Yes the 'setState' does the trick here.
whenever the setState called, the build method will be triggered to re-draw or re-build
Yes !! now you got the difference between Stateful and Stateless widget in flutter
Happy coding 😇😇 !!
Top comments (0)