Flutter: Stateless vs Stateful
What is a widget?
In Flutter everything is a widget. A widget is a building block for your user interface. Flutter uses widgets to create amazing apps
Flutter has several built-in widgets, and all of them are classified into two types:
Stateless
Stateful
To begin a comparison, we must first understand the current state of widgets.
The State of Widget
The state is information that can be read synchronously during widget construction and that may be modified later on.
Stateless
Stateless widgets are immutable.
- The stateless widget does not change after you build it.
- Used to display static information
- Stateless widgets are ‘DATALESS’ widgets as they don’t store real-time data.
Let’s examine the Stateless widget’s architecture.
Stateless widget with the name “MyApp” and its overrides build method. BuildContext is an argument in the build method, which returns a widget.
The Stateless Widget’s single-call build method is in charge of creating the user interface. Create a new instance of the stateless widget if you want to redisplay it.
Stateful
Stateless widgets are mutable.
- The stateful widget can be changed after you build it.
- Used for displaying dynamic data
- Stateful widgets are bound to data and automatically update as the data model changes
- If you want to update UI based on a certain event, use a stateful widget
- Need to use setState.
Let’s examine the Stateful widget’s architecture.
“SplashScreen” is a Stateful widget and it is an override “createState” method that returns the instance of the “_SplashScreenState” class.
The class “_SplashScreenState” extends from “State<>” which takes “SplashScreen” as a template input.
Finally “_SplashScreenState” override the build method and returns a widget. This build method can be called any number of times and every time it redraws the widget.
Conclusion
If a widget is not changing, it is a Stateless widget.
If a widget is changed, it is a Stateful widget.