Provider State Management in Flutter - Part 2
Tags: flutter, provider, dart
Published: 2022-08-02 13:42:00

**First of all :**

i recommend you to read part 1:
https://dev.to/eman55555/provider-state-management-in-flutter-part-1-e4k

_**In Part 1 we have seen only single provider implementation.****What about having  multiple providers declared in your flutter app ?**_

using provider you can expose the data and can observe it with the help of `consumer `through out your app.This will make a easy to access user friendly data usage. Flutter `Multiprovider `is required to handle some situations where we require different data objects or depending upon the modules so in this article we will be dealing with a example on them. Using the provider you can avoid all the unnecessary data hierarchies and can just make use of the data where ever required and also can properly dispose them after use.

**_Ok let's make an app have 2 screens .each of them uses different Provider like this :_**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bcpcplny30h25bn9r0y.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0p8vsiwiio2sqnuiitt.PNG)

**add the dependency for the provider pattern in the pubspec.yaml file.**
`flutter pub add provider`


```
dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  provider: ^6.0.3
```

**create your first model and add methods to increment / decrement / reset the counter, extend `ChangeNotifier` from the material.dart package. This provides us with the `notifyListeners()` method, and will notify all the listeners whenever we change a value.**


```
import 'package:flutter/material.dart';

class Counter with ChangeNotifier {
  int count = 0;
 //int get myCounter() => count;

  void incrementCounter() {
    count++;
    notifyListeners();
  }

   void decrementCounter() {
    if (count > 0) {
      count--;
    }
    notifyListeners();
  }

   void resetCounter() {
    count=0;
    notifyListeners();
  }
}
```
**create your second model and add a method to add item to   `List<String> _cart = ["Red", "Green", "Blue"]` , extend `ChangeNotifier` from the material.dart package. This provides us with the `notifyListeners()` method, and will notify all the listeners whenever we change a value.**


```
import 'package:flutter/material.dart';

class Cart with ChangeNotifier {
  final List<String> _cart = ["Red", "Green", "Blue"];
  int get count => _cart.length;
  List<String> get cart => _cart;

  

  void addItem(String item) {
    _cart.add(item);
    notifyListeners();
  }
}
```
**wrap your home widget with `MultiProvider` and inside it call `ChangeNotifierProvider<YOUR_MODEL_NAME>` widget to every model**


```
void main() {
  
  runApp(

    MultiProvider(
      
      providers:[
          ChangeNotifierProvider<Counter>(create: (_)=>Counter(),),
          ChangeNotifierProvider<Cart> (create: (_)=>Cart(),),

    ],
    child: MyApp(),
    ),
    
  );
}
```

**add `routes` in your MaterialApp widget**


```
@override
  Widget build(BuildContext context) {
    return 
       MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
       
        initialRoute: '/',
        routes: {
        '/' : (context) => HomePage(),
        '/second' :(context) => Second()


      },
      );
  }
}

```

**To update the text, call your variables and function from Your model to use them
wrap your text widget with `Consumer<YOUR_MODEL_NAME>` widget**

 

```
@override
  Widget build(BuildContext context) {
    return Consumer<Counter>(
      builder: (context, counter, child) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Home'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Text('${cart.cart}'),
                // Text('${context.watch<Cart>().cart}'),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('The Number : '),
                    // Text('${context.watch<Counter>().count}'),
                    Text('${counter.count}',
                        style: const TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 20)),
                  ],
                ),


```


**Source Code**: branch  " <u>`multiProvider`</u> "
{% embed https://github.com/eman55555/provider_state_management %}
                  
_**Congratulations 🥳🤩**_
_**you implemented multiProvider in Flutter Counter App !**_