When building Flutter apps, most of the time we are dealing with widgets. Widgets are everywhere in Flutter. Flutter uses widgets to describe reusable building blocks in the user interface. Comparing to other libraries, a widget in Flutter is a much broader concept. Not only common components like buttons and form inputs are widgets, but layout constraints are also expressed as widgets in Flutter. For example, if you want to place a widget in the centre of a box, you simply wrap the widget into a Center widget.

Today, we will understand about Stateless widget.

Stateful Widget

A widget is either stateful or stateless. A stateful widget have its own state and it can change—when a user interacts with it. StatefulWidgets themselves are immutable with states managed in State objects created by them.

A stateful widget is dynamic: for example, it can change its appearance in response to events triggered by user interactions or when it receives data.

For Example: Clicking on Checkbox, Selecting a Radio, Form, and TextField are examples of stateful widgets.

A StatefulWidget subclass needs to implement the createState() method that returns a State object. When the state changes, the State object should call setState() method to notify the framework to trigger the update.

Outline of Stateful Widget

Stateful widgets are dynamic components that have an internal state to manage. A stateful widget can react to state changes and change accordingly. The state is stored in a State object. To create a StatefulWidget, we have to extend the StatefulWidget abstract class, as shown in the following code:

The state will be a class extending the State abstract class. Let’s take a look at example where the widget changes the background color according to its state.

Example of Stateful Widget

Create a new Project in IDE or terminal, the directory structure of the new project will be looked like :

Project Directory
Project Directory

In this example we have Switch component, On performing ON and OFF will flip the color of the screen.

Here on change of the Switch, we have listener which sets the value of param value as ON/OFF [true/false as per boolean]. After setting up the param value we are calling setstate to refresh the component tree as per new State.

Stateful Widget

That’s it for now in StatefulWidget, Keep Learning and Sharing. 🙂

One Thought on “Stateful Widget in Flutter”

Leave a Reply

Your email address will not be published. Required fields are marked *