How to Add a Stateful Widget in Flutter

I used Stateless widgets in most of my previous Flutter tutorials. In this tutorial, let’s see how to add a Stateful widget in Flutter.

A Flutter widget can be either stateless or stateful. A stateless widget is static and never changes whereas a stateful widget is dynamic. The stateful widget can change itself. It uses State object where values that can be changed are stored. Using setState() method the values stored in State object can be changed and it results in the redraw of the widget.

Following is the basic structure of a Stateless widget.

class FavoriteWidget extends StatefulWidget {
  @override
  _FavoriteWidgetState createState() => _FavoriteWidgetState();
}
class _FavoriteWidgetState extends State<FavoriteWidget> {
}

Yes, FavoriteWidget extends subclass StatefulWidget whereas createState() returns an instance of _FavoriteWidgetState class.

Now, let’s move onto a real case of State usage for better understanding. In the following Flutter Stateful widget example, we have a text and a button. when the button is pressed the text shows how many times the button is pressed.

import 'package:flutter/material.dart';

class StatefulWidgetExample extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: MainScreen()
    );
  }
}

class MainScreen extends StatefulWidget {
  MainScreen({Key key}) : super(key: key);

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {

  int count = 0;

  void add() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      count++;
    });
  }
  @override
  Widget build(BuildContext context) {
        return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
  child:Column(
        children: <Widget>[
        Text('$count',
        style: TextStyle(fontSize: 48)),
        RaisedButton(
          child: Text('Add'),
          onPressed: (){add();},
        ),
        ]
      ),
    ),
    );
  }
}

Look close to the add() function. It uses setState() to change the value of variable count. As a result, each time the value of count is changed the widget is redrawn with new value of count. Check the output of the Flutter example below.

flutter stateful widget

I hope you find this tutorial helpful.

1 thought on “How to Add a Stateful Widget in Flutter”

  1. Pingback: How to Create a Text Input in Flutter – Flutter For You

Leave a Comment

Your email address will not be published. Required fields are marked *