Stateless and Statefull widget
Today I decided to talk a little bit about the difference between a stateless and stateful widget , in this post I will cover a brief and simple explanation and show you how to use them when we start building flutter apps
for example for android native architecture we know that to build a user interface we will need to create a class that extends an Activity , which consists a user interface scope and has a lifecycle starting from initial creation into destruction and similarly to flutter to create a user interface we will need a class which extends one of those famous widgets and has some kind of lifecycle scope called state and has build method called when it’s first inserted to the widget tree we can give it an equivalent of onCreate method of Android Activity class.
so what is a stateless or state full widget and what’s the difference between them
A stateless widget is used to create a user interface and doesn’t require a mutable state it is used to cover other UI widgets in the tree but when something changed on those widgets during it’s runtime it doesn’t impact it’s state and it remains unchanged until next build re run
so as a recap we will need a stateless widget only when we are sure that e our widgets doesn’t require data changes at runtime
example :
class StatelessWidgetExample extends StatelessWidget {
const StatelessWidgetExample({ Key key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(color: const Color(0xFF2DBD3A));
}
}
A stateful widget is used to create a user interface and it does require mutable state it also cover other UI widgets in the tree
each stateful widget has it’s own state and it might change during widget lifetime this means it’s build method re called for any change at the lifetime which make the user interface update their data and the way it looks at real time
example :
class StatefulWidgetExample extends StatefulWidget {
const YellowBird({ Key key }) : super(key: key);
@override
_ StatefulWidgetExampleState createState() => _StatefulWidgetExampleState();
}
class _ StatefulWidgetExampleState extends State {
@override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}
I think it’s simple now we can start creating our own user interfaces and make our widgets inherit from either stateless or stateful depending on our situation