State management in Flutter apps using Provider

Hello everyone, I hope you all are doing great. Today I am going to talk about State Management in Flutter apps. So first at all let’s find out what exactly state means…

What is State in Flutter?

“State is information that can be read synchronously when the widget is built and might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using State.setState.” -Flutter official documentation

Okay let’s figure it by our self. If you are a react or react native developer you have probably heard the word about state. Simply state is a variable or a value that can be dynamically change in run time. For an example let’s assume that you have created a flutter app to buy shopping items. So you probably have a cart in your system. For simplicity let’s assume that cart is list of Strings.

So where do you gonna put this state? Probably inside a screen call cart that has a state-full widget right?

This is the normal way that you going to do. It’s okay to do that way. But let’s figure out the problems that you are going to face in this process. First take a look at the following picture.

As you can see you have your screen or the widget as MyCart and inside that you have it’s state. You can change the state inside that widget. Or if you have any other child widgets for MyCart, in that case also you can access/change the state inside that child components as well. But what about the MyAppBar widget or MyLoginScreen????

There is no way you can access/change your cart state inside in those widgets. So how are we going to solve this problem? The answer is pretty simple, using a state management.

How state management system/tool is going to help with this?

A state management tool will provide a way to provide your state into several widgets by lifting up into the top level in your widget tree.

As you can see after using state management tool, your state is available to all of your widgets/screens.

What are the famous state management tool available for Flutter?

  • Provider
  • InheritedWidget & InheritedModel
  • SetState
  • Redux
  • Fish-Redux
  • BLoC/Rx
  • Flutter Commands
  • GetIt
  • MobX
  • Riverpod
  • GetX

That’s a lot, So what is the recommended way to handle state in flutter?

  • Provider is the recommended state management tool that is recommended by the flutter team.

So let’s create a simple application that can increase a value and manage it’s state using Provider.

  1. Create a new flutter application
flutter create statedemo

2. Navigate into project folder

cd statedemo

3. Add the Provider dependency to the project

flutter pub add provider

4. Create a new folder name “Providers” inside lib folder

mkdir Providers

5. Inside that Provider folder create dart file name “counter_provider.dart”

touch counter_provider.dart #linux
echo -> counter_provider.cart #windows

6. In “counter_provider.dart” create a class name Counter with ChangeNotifier

//The with keyword indicates the use of a "mixin"//A mixin refers to the ability to add the capabilities of another //class or classes to your own class, without inheriting from those //classes.import 'package:flutter/material.dart';class Counter with ChangeNotifier {     int _count = 0;     //to access to the state
int get count => _count;
//to increment the state
void increment() {
_count++;
notifyListeners();
}
}

Now we successfully separate our state from the widget. Now let’s use this in our application.

7. Let’s provide our state to root app widget so any widget can use our state.

7.a). import required files

import 'package:flutter/material.dart';
import 'package:{PROJECT_NAME}/providers/counter_provider.dart';
import 'package:provider/provider.dart';

7.b).

void main() {
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => Counter())],
child: MyApp(),
));}

If you have more than 1 state, you can put those into the providers list

Now you can access/change the state using the respective methods that we created on the Counter class

For an example if you want to access the counter state inside your widget

context.watch<Counter>().count

To increment the state

onPressed: () => context.read<Counter>().increment()

Software Engineer 2 at Arimac || Data science | Machine learning | Deep learning Enthusiast || SE Undergraduate

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Powerful Language of Javascript

How to Convert .seq Files into MP4

How to Whitelist AmPmCx Emails

An Opinionated Guide to React

How to deploy a strict Content Security Policy (CSP) with Next.js

Save clicks with the new Chrome extension for Webflow

Chrome Extension: My projects in Webflow

Next JS — Build for Production

Doing some SVG drawings on a web page (Raphael.js)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shihara Dilshan

Shihara Dilshan

Software Engineer 2 at Arimac || Data science | Machine learning | Deep learning Enthusiast || SE Undergraduate

More from Medium

Flutter Error: No pubspec.yaml file found. How to fix it?

flutter No pubspec.yaml file found

Sharing QR code in Flutter

Advantages of Developing a Mobile App Using Flutter

Customize Flutter Snackbar Example