Flutter State Management With Provider and ChangeNotifier

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it’s so important? There are lots of topic in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.

Basic knowledge of the state management and data flow in the Flutter

Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it’s important to manage the state of your application in the correct way.

In Flutter, everything is a widget and whenever the state of your application changes the UI are recreated the UI with the new data. Let’s list out the topic or problem that we are going to explore about state management.

Challenge of State Managemen in Flutter without any model

  • If every data change recreated the application widget the primary issue is the performance.
  • The complexity of accessing the data from other widgets.
  • Problem and Complexity involved if we want to move a widget from one page to other pages, in other words from one widget tree hierarchy to another widget tree. You need to do lots of changes to move the data flow logic just to access the data.
  • There are multiple solutions to this but which are the best among that is sometimes difficult. So will try to help on that topic as well in this article.

I understand that if you are new to flutter then it’s difficult to understand the logic of state management and why it’s so important. It’s okay from small, we don’t care about the state management but as application complexity will grow you will realize that we need some model to manage the state of the application.

Just, for example, we have two pages in our application. On the first page, we have listed all item which can be added by the user and later when tabbing the user to second screen all the selected item need to show on the second page. So how you will do this?

The easy way is that we can pass the parameter while routing the user to the second page, but what if the same data is required on some other page. We have to write same again for this page and send the data to the down the hierarchy by sending the data widget by widget at the required place.

If you don’t know about how to navigate to the other page in flutter then you can refer our earlier tutorial on Page Navigation In Flutter

Prerequisite to use the Provider for State Management

If we create a flutter application then we get the default code with the counter as given below.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
     
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter State Management Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
   
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), 
    );
  }
}

This default application increases the counter value when the user taps on the floating action button and show into the text in the center of the home page. So, first of all, we will break this default application in three parts to convert it into the model.

Configure the Your Flutter Project to use Provider Package

First of all, we need to add the provider library as a dependency in project pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  provider:

After adding the above line click on get package to add it as a dependency in your project.

Create a Counter Model with ChangeNotifier

So we are now going to create a model which will we responsible for providing the updated value to our widget and whenever value counter value change due to any event it will notify the all the respective widget to recreate with the latest value.

There two functions inside this model one will increase the value and others will decrease the value of the counter.

import 'package:flutter/foundation.dart';

class MyCounter with ChangeNotifier{
  //internal counter
  int  _counter=0;
//This is getter function
  int get counter => _counter;
//This is setter and set the value and notify about change
  set counter(int counter){
    _counter=counter;
    notifyListeners();  }
//increment function
  increment(){
    counter=counter+1;
  }
  //decrement function
  decrement(){
    counter=counter-1;
  }
}

If you notice in the above code we use the notifyListeners() function and this function is responsible for notifying the all the widget about the change whenever counter value will change. This function comes from the foundation.dart package. So don’t forget to import this function.

Create a Stateless Widget for our home page to demonstrate Flutter State Management with Provider

let’s create a stateless widget with two-button and text to show the counter value.

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text("$title"),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
             Text(
                '',
                style: Theme.of(context).textTheme.display1,
              ),
            RaisedButton(
              onPressed: (){  }  ,

              color: Colors.blue,

              child:Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.add,color: Colors.white,),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                    child: Text("Increment",style: TextStyle(color: Colors.white,fontSize: 20)),
                  )
                ],
              ),
            ),
            RaisedButton(onPressed: (){ },
              color: Colors.blue,
              child:Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.remove,color: Colors.white,),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                    child: Text("Decrement",style: TextStyle(color: Colors.white,fontSize: 20),),
                  )
                ],
              ),
            ),
          ],
        ),
      ),);
  }
}

When you click on the increment and decrement function then it will do nothing because there is no event added to it on the pressed section of the raised button.

Flutter State Management Demo

Now time to add the provider to our application in the main section of our app. There are two types of provider a single provider in which you can add the only one provider and another one is multi-provider.

We are using the multi-provider in this example but depending on your requirement you can use any of this.

If you check the default application then it’s returning a material app. Now we will wrap this inside a provider like below.

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<MyCounter>.value(value: MyCounter(),)
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter State Management Demo'),
      ),
    );
  }
}

The important line in the above code is given below, this line of code provides access of counter value to all of our widget as well as access to all of the function inside our counter class.

return MultiProvider(
providers: [
        ChangeNotifierProvider<MyCounter>.value(value: MyCounter(),)
      ],

Use the Change Notifier Provider in our application

For using the value we just need to call the provider of method like below.

 Text(
                '${Provider.of<MyCounter>(context).counter}',
                style: Theme.of(context).textTheme.display1,
              ),

How to call the function of the Model using the provider

For calling the increment and decrement function of MyCounter model we can use it as given below.

Provider.of<MyCounter>(context,listen: false).increment()
Provider.of<MyState>(context,listen: false).increment();

Now test the application you will see that the value is getting updated on click on increment and decrement button.

So, are we are able to flow the data from the top to bottom and we can use this value at anywhere in our widget hierarchy. So our major problem of data access has been solved.

But there is a problem with it still our whole screen is getting rebuild after every increment and decrement.

How to check the application UI rebuild status for flutter state management with provider

So for checking this just tab on performance option in right bottom corner of android studio and check on show widget rebuild information inside the widget rebuild stats.

If you see in the above screenshots then you can see that on every click our home page is getting rebuild. It’s fine for a small application like this but what if we have lots widget which is very heavy. It will impact the performance of our application very badly.

Use the Consumer widget to get out of the UI rebuild problem

The solution of this problem is wrapping our text widget with Consumer widget like this.

 Consumer<MyCounter>(
               builder: (BuildContext context, MyCounter value, Widget child) =>
               Text(
                  '${${value.counter}',
                  style: Theme.of(context).textTheme.display1,
                ),
             ),

But after doing this as well our problem are not resolved and full UI is getting rebuild. It is because we are still using the provider directly and listening to it in the raise button.

Now stop listing the provider method inside the raised button. For stoping this just add the listener:false in your button like below.

  RaisedButton(onPressed: (){  Provider.of<MyCounter>(context,listen: false).decrement();},

Now test it again you will see that only your text widget is getting rebuild and rest of the widget in your hierarchy will remain unchanged.Look at below screen shot.

That’s all in this article below is the full code of the above example for your reference.

Full Source code of basic Flutter State Management with Provider

import 'package:flutter/foundation.dart';

class MyCounter with ChangeNotifier{
  //internal counter
  int  _counter=0;
//This is getter function
  int get counter => _counter;
//This is setter and set the value and notify about change
  set counter(int counter){
    _counter=counter;
    notifyListeners();  }
//increment function
  increment(){
    counter=counter+1;
  }
  //decrement function
  decrement(){
    counter=counter-1;
  }
}
import 'package:flutter/material.dart';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';

import 'counter.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<MyCounter>.value(value: MyCounter(),)
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter State Management Demo'),
      ),
    );
  }
}
class MyHomePage extends StatelessWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text("$title"),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
             Consumer<MyCounter>(
               builder: (BuildContext context, MyCounter value, Widget child) =>
               Text(
                  '${value.counter}',
                  style: Theme.of(context).textTheme.display1,
                ),
             ),
            RaisedButton(
              onPressed: (){  Provider.of<MyCounter>(context,listen: false).increment(); }  ,

              color: Colors.blue,

              child:Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.add,color: Colors.white,),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                    child: Text("Increment",style: TextStyle(color: Colors.white,fontSize: 20)),
                  )
                ],
              ),
            ),
            RaisedButton(onPressed: (){  Provider.of<MyCounter>(context,listen: false).decrement();},
              color: Colors.blue,
              child:Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(Icons.remove,color: Colors.white,),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0,horizontal: 16.0),
                    child: Text("Decrement",style: TextStyle(color: Colors.white,fontSize: 20),),
                  )
                ],
              ),
            ),
          ],
        ),
      ),);
  }
}

Some reference to Provider

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Feedback and Suggestion

Close Menu