How to Create Stateful Widget in Flutter

In this tutorial, we will create a button widget, and when the button is pressed, it will add an item to the List and display that List on the mobile screen. So, when the button is pressed, the widget’s state will change, the UI will be re-rendered, and we will see the products list inside the mobile screen.

If you do not know how to install flutter on the mac, you can check out this article. It will walk you through installing the flutter app and opening an app on both Android and iOS simulators.

How to Create Stateful Widget in Flutter

To create a stateful widget in a flutter, use the createState() method. The stateful widget is the widget that describes part of a user interface by building a constellation of other widgets that represent a user interface more concretely.

A stateful Widget means a widget that has a mutable state. The state is information that can be read synchronously when the widget is built and might change during a widget’s lifetime. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using the State.setState method.

The building process continues recursively until a user interface description is sufficiently concrete.

After creating a new project, your project structure looks like this. Remember,  I am using Flutter version 1.0. So, if you have a different structure, please check the version of your project.

How To Create Stateful Widget In Flutter

We will change only one file for this example, lib >> main.dart file.

Skeleton of Stateful Widget

The following is the basic syntax of any Stateful Widget class.

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}

So, here first, we have declared our main class called MyApp, which extends the StatefulWidget class. That means we have to define the generic method called createState() in that class.

Now, that method will return one another class which extends the State.

In our case, the _MyState class extends the State. So all the coding related to state updation is inside this class.

createState method

It creates the mutable state for that widget at a given location in the tree. For example, the following code implements it.

@protected
State createState();

Example of Stateful Widget

We are taking one example in which we will add a button and a card. The card consists of one widget called Text. So when a user clicks on a button, it will add a new item to the list. So the state of the list is changed, and flutter will update its UI, and we will see the lists on the mobile screen.

Now, replace the following code with an existing code inside the lib >> main.dart file.

// main.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  List<String> _products = ['Laptop'];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('First app')),
        body: Column(children: [
          Container(
              margin: EdgeInsets.all(10.0),
              child: RaisedButton(
                  onPressed: () {
                    setState(() {
                      _products.add('PC');
                    });
                  },
                  child: Text('Hello World'))),
          Column(
              children: _products
                  .map((element) => Card(
                        child: Column(
                          children: <Widget>[
                            Text(element)
                          ],
                        ),
                      ))
                  .toList()),
        ]),
      ),
    );
  }
}

The List data type is equivalent to an Array of the Javascript language. Therefore, you can add or remove the elements from the list.

Inside the _MyApp class, we have initialized one list called _products with one item called Laptop. So that is our state variable for this demo.

Now, when a user clicks on a button, it will call the setState() method, which will add the new item on the list, and due to change in state, the flutter updates the UI, and we are iterating a card widget based on the list and see the text on the screen.

How to add data in flutter list example tutorial

When a user clicks on a button, we will see that a PC item will be added every time on the list, and you can display that item in the form of a card on the screen.

So, this is how you can work with StatefulWidget in the flutter.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.