Stateful and Stateless Widget

Compare how stateful and stateless widgets can help us to build our UI with Flutter.

To make any Dart class a Flutter widget, we have to extend that class. This class can extend either StatelessWidget or StatefulWidget abstract classes. These two widget classes come shipped with Flutter SDK. We’ll go over both abstract classes in detail.

State

The state is a change in our domain objects. Assume we are making an Instagram app in which we have a post domain object with fields like postedBy, createdAt, numberOfLikes, etc.

These fields together make up a state for this particular post object. Now suppose a follower clicks the “Like” button on this particular post. The numberOfLikes changes, so basically, the state changes. Whenever a state changes, we as a developer have two options—either to show the updated state (numberOfLikes in this example) or not to show it to the users.

Stateful and stateless widgets

Since we now have an idea of what a state is, we’ll learn more about StatelessWidget and StatefulWidget. Whenever we want to build a UI element on the screen that needs to be updated upon user interaction or if we want to change the state, use StatefulWidget. Otherwise, we use StatelessWidget.

If we always use StatefulWidget, then also we’ll be able to complete the app, but, we will suffer some decrease in performance. Stateless widgets are built only once on the screen, hence, it improves the performance of the app.

Example of StatelessWidget

Let’s see an example of a StatelessWidget.

Note: Please go through the comments in the code below to understand the widget better.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy