Stateful and Stateless widgets in Flutter
Flutter

Stateful and Stateless widgets in Flutter

Mishel Shaji
Mishel Shaji

In this post, we'll learn about Stateful and Stateless widgets. We'll also see what is:

  • A State
  • Difference between Stateful and Stateless widget.
  • Steps involved in creating a Stateful widget.

Stateful vs Stateless widget

Stateless widgets are the widgets that don't change. Its appearance and properties remain unchanged throughout the lifetime of the widget.

To create a Stateless widget, we have to override the build() method.

Eg: Text widget.

Widgets that changes it's properties during run-time are Stateful widgets. To create a Stateless widget, we have to override the createState() method, which returns the state of the widget.

Eg: CheckBox, RadioButton.

What is a State?

The state can be defined as the information about a widget. The state may change during the lifetime of a widget.

Create Stateful widgets

Creating a Stateful widget includes three steps.

Step 1: First we should create a class that extends from StatefulWidget class and it should return the state of the widget in the createState() method.

import 'package:flutter/material.dart';

class MyStatefulWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return null;
  }

}

Step 2: Next, we should create a State class along with the properties of the widget that might change.

Step 3: The state class should implement the build() and setState() methods to manage the state of the widget.

import 'package:flutter/material.dart';

class MyStatefulWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyStatefulWidgetState();
  }

}

class MyStatefulWidgetState extends State<MyStatefulWidget>{
  String property1 = 'Value 1';

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        TextField(
          onSubmitted: (String s){
            setState(() {
              property1 = s;
            });
          },
        ),
        Text("Hi.. You typed $property1"),
      ],
    );
  }

}
Calling setState() method will tell the framework to destroy the widget and redraw it with new properties.

In the next post, I'll explain how to create a Stateful widget in our application.