Flutter – Sharing data between muliple Providers

Issue

I am building a Flutter app that has a main provider that contains a session id and lots of other "global" properties.

class AppService with ChangeNotifier {
    String _sessionId;
    String _name;
    ...
}

I have also got several other Providers that handle very specific things (also AppService was starting to get large so had to split it out).

My question is how do i access _sessionId, name and other properties in AppService from other services (named them ServiceB, ServiceC and ServiceD for example)? Also is it possible to call functions in AppService from another such as ServiceB?

class ServiceB with ChangeNotifier {
    ...
}

class ServiceC with ChangeNotifier {
    ...
}

class ServiceD with ChangeNotifier {
    ...
}

I have seen some mention of ChangeNotifierProxyProvider, but not sure if this will give me what i need as i need to have access the AppService in multiple other classes.

Here is how my providers are currently setup..

MultiProvider(
    providers: [
      ChangeNotifierProvider<AppService>(
        create: (_) => AppService(),
      ),
      ChangeNotifierProvider<ServiceB>(
        create: (_) => ServiceB(),
      ),
      ChangeNotifierProvider<ServiceC>(
        create: (_) => ServiceC(),
      ),
      ChangeNotifierProvider<ServiceD>(
        create: (_) => ServiceD(),
      ),
    ],
    child: const InitSysApp(),
  )

Solution

You can use ProxyProvider from the provider pub

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

    class Person with ChangeNotifier {
      Person({this.name, this.age});

      final String name;
      int age;

      void increaseAge() {
        this.age++;
        notifyListeners();
      }
    }

    class Job with ChangeNotifier {
      Job(
        this.person, {
        this.career,
      });

      final Person person;
      String career;
      String get title {
        if (person.age >= 28) return 'Dr. ${person.name}, $career PhD';
        return '${person.name}, Student';
      }
    }

    void main() {
      runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider<Person>(
                create: (_) => Person(name: 'Yohan', age: 25)),
            ChangeNotifierProxyProvider<Person, Job>(
              create: (BuildContext context) =>
                  Job(Provider.of<Person>(context, listen: false)),
              update: (BuildContext context, Person person, Job job) =>
                  Job(person, career: 'Vet'),
            ),
          ],
          child: MyApp(),
        ),
      );
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: MyHomePage(),
        );
      }
    }

    class MyHomePage extends StatelessWidget {
      const MyHomePage({Key key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Provider Class'),
          ),
          body: Align(
            alignment: Alignment.center,
            child: Container(
              padding: EdgeInsets.all(20.0),
              decoration: BoxDecoration(
                border: Border.all(),
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    'Hi, may name is ${context.select((Job j) => j.person.name)}',
                    style: Theme.of(context).textTheme.headline6,
                  ),
                  Text('Age: ${context.select((Job j) => j.person.age)}'),
                  Text(context.watch<Job>().title),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () =>
                Provider.of<Person>(context, listen: false).increaseAge(),
          ),
        );
      }
    }

Answered By – Hemanth S

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *