Stateful Widget vs Stateless Widget — Flutter

Sandali Tharuki
3 min readJan 9, 2021

Stateful Widget

As the name itself says the Stateful widget has a mutable or changeable state. The state of the Stateful widget can be changed during the lifetime of the widget. The state can be read synchronously. The Stateful widget is the concrete for other widgets and other widgets are built upon the Stateful widget. The widget tress actually builds in the State class of the Stateful widget. It is advised to use the Stateful widget when the UI is needed to change dynamically. When the state of the Stateful widget is changed, setState() should be called in order to recreate the widget. createState() and return state override the previous widgets.

Sample Code — Creating a Stateful widget

In creating a Stateful widget 2 classes are required. They are the widget itself and the State. The widget tress actually builds in the State class of the Stateful widget. The createState() is used to create a Stateful widget. We can simply type stful + tab key to create a Stateful widget. If it is needed to change a Stateless widget into a Stateful widget, press alt + Enter on Android Studio and ctrl + . on Visual Studio Code. It is as simple as that.

Stateless Widget

As the name itself says the state of the Stateless Widget, is not changeable. Once we create a Stateless widget it remains as it is during its lifetime. It is advised to use the Stateless widget when the specific part of the UI does not subject to change by anything. As the Stateful widget, the Stateless widget also acts as the concrete for other widgets.

Sample Code — Creating a Stateless widget

Creating a Stateless widget significantly changes from creating a Stateful widget. As in the Stateful widget, the Stateless widget does not have two classes. The Stateless widget only contains one class, the widget itself. BuildContext is the build method that is used to create a Stateless widget. Simply type stless + tab key to create a Stateless widget and it is as simple as that.

Summary

Stateful Widget

  1. The state of the widget is mutable
  2. Use when the UI needs to change dynamically
  3. Overrides the createState() and returns
  4. CheckBox, RadioButton, Form, TextField

Stateless Widget

  1. No state to be changed
  2. Use when the content of UI is static
  3. Overrides the build() and returns
  4. Text, RaisedButton, Icon, IconButton

This is the end of the article. Hope this article would be helpful for you.

Thank You!!!

--

--

Sandali Tharuki

Undergraduate-Faculty of Information Technology | University of Moratuwa | Sri Lanka