Stateless & stateful widgets

In this lesson, stateless & stateful widgets are discussed in detail.

We'll cover the following

Stateless widget

  • A Stateless widget is immutable. Once it’s created, it can’t be changed. It doesn’t preserve its state.
  • Stateless widget is drawn only once, and it can not be redrawn at a later time.
  • Stateless widget’s build() method is called only once.

Let’s use the Container widget to understand creating a custom StatelessWidget.

Container Widget: A container widget is a convenience widget that combines common painting, positioning, and sizing widgets.

The following code snippet demonstrates how a Container widget is created in a stateless manner. This widget is created only once.

class MyStatelessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
  • Few examples of Stateless widgets are below. Once they are created, their value can’t be changed. If the value of the stateless widget needs to be changed then new widgets need to be created with the updated value.

  • Some of the examples of Stateless widgets are below. Stateless widgets don’t keep track of their state.

    • Text widget: It contains the immutable string of letters.
    • Icon widget: The icon widget is immutable and not meant for interaction.
    • Card widget: It is a material design card which is used to show relevant information.

Get hands-on with 1400+ tech skills courses.