When developing with Flutter, there will certainly be a need of building screen layouts, customizing existent user interfaces or managing how the screen changes with user’s interaction. Due to this, the developer must know how to deal with widgets and in this article we’ll cover the two classes that give origin to every single widget available in Flutter.
First, let’s understand how a widget is different from other classes and how Flutter renders its content on the screen. A widget is a class which holds a very particular method: the “build” method. It is nothing but a function that is executed when its parent widget has its build function executed. Of course, there must be an initial trigger, which is done automatically by Flutter when it initializes the application. The build function basically renders (i.e. draws) the layout of its widget on the screen of the device where the app is being run. In summary, if you want to render something on the screen, just choose a widget and execute its build function. It is that simple. Flutter does all the hard work in the background.
Now, there are two different classes of widgets available in Flutter: StatelessWidget and StatefulWidget. A StatelessWidget does not have any state while a StatefulWidget does. A state can be any data within the widget object that defines it at a given moment. Let’s say, for example, that we have an expandable card in our app. A good state variable for this case would be a boolean property (true or false only values) that tells Flutter whether the card is currently expanded or not.
– Expanded: false.
– Expanded: true.
This means that the boolean “expanded” property of the object is determining how the widget is being rendered, and thus is a state variable for this object. In this case, this widget needs to extend (i.e. inherit) from the StatefulWidget class, since the StatelessWidget class can’t have states.
The main reason why StatelessWidgets can’t have states is because they don’t have means for executing the build function more than one time. This is the biggest difference between these two classes. A StatefulWidget has a method called “setState”, which is a function that executes some lines of code (usually in order to update a state variable) and then executes the build function. Since the build function will run again, the widget layout that is being rendered on the screen will be rebuilt, accounting for any differences that the state variables might have from before. Therefore, a StatelessWidget will never be able to execute the build function more than once due to the lack of the setState function.
In the image shown below, we can see some examples of stateless and stateful widgets: highlighted in green, we have StatefulWidgets, and in red, StatelessWidgets. Definitely, stateful ones are responsible for providing interactions with the user.