When to use Stateful Widget in Flutter, E Com App 11

When do we use stateful widget in flutter? We’ll discuss. Before that, let’s understand what a StatefulWidget means.

As the name suggests, a stateful widget has a mutable state. In short, a widget that changes the user interface when a user interacts with the widget.

For example the user presses a button and a section of the user interface changes its color.

We have seen before, State might be of two types. Local and global. 

Besides that, State is information or data that we can read when the widget rebuilds. 

Any widget has a lifetime, and in that lifetime, it might change. The State helps to change.

When we use State.setState, it notifies the State when such State changes.  

But the question is when do we use the stateful widget? Because as we have been building the E Commerce app, we have used the Provider package. 

As a result, we can manage the State with Provider and a StatelessWidget

Not only it reduces the widget-rebuilds, but also reduces the misuse of the BuildContext.

Therefore, we must have a reason to use a StatefulWidget.

How a stateful widget works, we will discuss in the next section. 

Why?

Because a Flutter developer must know how State changes.

Why we’ve used the StatefulWidget

In our previous section we have seen the pop up menu item that displays the options to choose between two widgets.

As an outcome, a user who has already tapped the favourite icons, gets all the favourite items in one page.

Pop up menu on the right hand top corner shows both options
Pop up menu on the right hand top corner shows both options

Pop up menu will show only favorite items on the page
Pop up menu will show only favourite items on the page

We have managed that State changes through the StatefulWidget instances.

import 'package:flutter/material.dart';

import '../controllers/products_grid.dart';

enum FilterOptions {
  favorites,
  all,
}

class ProductsOverviewScreen extends StatefulWidget {
  const ProductsOverviewScreen({Key? key}) : super(key: key);
  @override
  State<ProductsOverviewScreen> createState() => _ProductsOverviewScreenState();
}

class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> {
  var _showOnlyFavorites = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('E-Commerce App'),
        actions: <Widget>[
          PopupMenuButton(
            onSelected: (FilterOptions selectedValue) {
              setState(() {
                if (selectedValue == FilterOptions.favorites) {
                  _showOnlyFavorites = true;
                } else {
                  _showOnlyFavorites = false;
                }
              });
            },
            icon: const Icon(
              Icons.more_vert,
            ),
            itemBuilder: (_) => [
              const PopupMenuItem(
                value: FilterOptions.favorites,
                child: Text('Only Favorites'),
              ),
              const PopupMenuItem(
                value: FilterOptions.all,
                child: Text('Show All'),
              ),
            ],
          ),
        ],
      ),
      body: ProductsGrid(_showOnlyFavorites),
    );
  }
}

In summary, we have managed the local state and as a result it does not affect the state across the app. 

That’s the primary reason why we have used a StatefulWidget for the product overview screen.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Python and Data Science

Twitter

Comments

Leave a Reply