DEV Community

Cover image for Provider State Management in Flutter - Part 2
Eman Hamad
Eman Hamad

Posted on

Provider State Management in Flutter - Part 2

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 consumerthrough out your app.This will make a easy to access user friendly data usage. Flutter Multiprovideris 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

Image description

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
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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(),
    ),

  );
}
Enter fullscreen mode Exit fullscreen mode

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()


      },
      );
  }
}

Enter fullscreen mode Exit fullscreen mode

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)),
                  ],
                ),


Enter fullscreen mode Exit fullscreen mode

Source Code: branch " multiProvider "

read this article for more details :

Dev : https://dev.to/eman55555/provider-state-management-in-flutter-part-1-e4k

Medium : https://medium.com/@emanhamad55555/provider-state-management-in-flutter-part-1-b3fcb9fd2226

provider_state_management

A new Flutter project.

Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter development, view the online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Congratulations 🥳🤩
you implemented multiProvider in Flutter Counter App !

Top comments (0)