AppDividend
Latest Code Tutorials

How To Create Stateful Widget In Flutter

0

In this tutorial, we will see How To Create Stateful Widget In Flutter. 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 lifetime of a widget. 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 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. The building process continues recursively until a description of a user interface is sufficiently concrete.

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 state of the widget will change, and the UI will be re-rendered, and we will see the products list inside the mobile screen.

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

How To Create Stateful Widget In Flutter

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, then please check the version of your project.

 

How To Create Stateful Widget In Flutter

We will change only one file for this example, and it is 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 now 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, it is the _MyState class which 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. It is implemented by the following code.

@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 to 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 datatype is equivalent to an Array of the Javascript language. You can add, remove the items 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 PC item will be added every time on the list and you can display that item as a form of a card on the screen.

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

Here, How To Create Stateful Widget In Flutter Tutorial With Example article is over.

Leave A Reply

Your email address will not be published.

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