Managing State with Stateful Widgets in Flutter

Tutorial 2 of 5

Introduction

In this tutorial, we’ll explore the concept of managing state with Stateful Widgets in Flutter. The state is a crucial concept that enables you to create dynamic and interactive apps.

By the end of this tutorial, you will learn:

  • What a Stateful Widget is
  • How to create a Stateful Widget
  • How to manage the state of a Stateful Widget

Prerequisites:
You should have a basic understanding of Dart and Flutter. It would also be beneficial if you have some experience with Stateless Widgets.

Step-by-Step Guide

Stateful Widgets are dynamic. The UI changes over time due to user interaction or real-time data updates. In Flutter, Stateful Widgets have mutable state.

Creating a Stateful Widget:
A Stateful Widget in Flutter is created in two steps:
- Create a class that extends StatefulWidget
- Create a separate class that extends the State class

Managing State:
The state of a widget can change over time. The state could be user input or data fetched from a database.

Code Examples

Here is an example of a simple counter app implemented with a Stateful Widget.

// importing Flutter package
import 'package:flutter/material.dart';

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

// Creating a Stateful Widget
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

// Creating the State
class _MyAppState extends State<MyApp> {
  int _counter = 0;  // Declare a variable for the counter

  void _incrementCounter() {
    setState(() {
      _counter++;  // Increment the counter when the button is pressed
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter App'),
        ),
        body: Center(
          child: Text(
            'Button pressed $_counter times',
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

In this code:
- We declare a variable _counter to hold the state of the counter.
- We define a function _incrementCounter to increment the counter. We use the setState function to tell Flutter that the state has changed and the UI needs to be updated.
- In the build function, we display the counter value in a Text widget.

The expected output will be a Flutter app with an appBar titled 'Counter App', and a floating action button. When the button is pressed, the counter increments and the updated value is displayed on the screen.

Summary

In this tutorial, we learned about Stateful Widgets in Flutter and how to manage their state. We also looked at a practical code example.

Your next steps could be to learn about more complex state management techniques, like using the Provider package or the Bloc library.

Practice Exercises

  1. Create a Stateful Widget that displays a different text message every time a button is pressed.
  2. Create a Stateful Widget that changes the color of a container every time a button is clicked.

Here are some resources to deepen your understanding:
- Flutter's official documentation on Stateful Widgets
- A video tutorial on StatefulWidget

Solutions

  1. You can use a List of Strings for the messages, and change the index each time the button is pressed.
  2. You can use a List of Colors for the container, and change the index each time the button is pressed. Remember to use setState to indicate that the state has changed and the UI needs to be rebuilt.