Stateless and Stateful Widgets in Flutter

In Flutter there are basically two types of widgets, Stateless widgets and Stateful widgets. If you don't know what widgets are, you can visit our Widgets and Flutter tree structure article. That being said, let's see the definition and difference of each type of widget.
Before seeing each definition, we must know what mutable state is. When we talk about mutable state in Flutter, we refer to any property that can change over time. Imagine this as a part of the user interface that can be updated through some interaction.
Stateless widgets
Stateless widgets are widgets whose state cannot change over time. In other words, they do not contain any mutable state that needs to be tracked. Imagine a text widget that contains the user's name. If the user's name doesn't change, it's a perfect candidate to be stateless.
Stateful widgets
Stateful widgets are widgets whose state can change over time. In other words, they contain some mutable state that needs to be tracked. Imagine a text widget that displays the number of times a button has been clicked. Since the text that displays such interaction changes with each click, it's a perfect candidate to be stateful.
Hot reload
Hot reload is a feature that allows for much faster application debugging by injecting the necessary files to the Dart Virtual Machine (VM). Once the VM is updated with the new files, Flutter will automatically update the widget tree, allowing you to see changes quickly.
This is important because there is no need to re-run the application from scratch but simply update the modified file (CTRL + S) and we will automatically have the changes in the application debug. For this, it is important to note that changes will be seen as long as the modified widgets are stateless. Let's see the following example:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Home()
));
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hot reload example'),),
body: Center(
child: Text('Hello World!',
style: TextStyle(fontSize: 40.0)
)
),
);
}
}
In this application we create a widget called Home
that extends StatelessWidget
and places the text Hello World! in the center of the body. Because this widget is stateless, any change we make to it will be reflected once changes are saved in the file. You can try creating a similar application and changing some part of the text. Later, you need to make sure to execute the command to do the hot reload, usually CTRL + S, you don't have to re-run the entire application!.
Finally, don't forget that if a property has the particularity of changing over time, then the widget containing this property must be stateful and not stateless. Until next time!.