Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a provider inside of another provider in Flutter

I want to create an app that has an authentication service with different permissions and functions (e.g. messages) depending on the user role.

So I created one Provider for the user and login management and another one for the messages the user can see.

Now, I want to fetch the messages (once) when the user logs in. In Widgets, I can access the Provider via Provider.of<T>(context) and I guess that's a kind of Singleton. But how can I access it from another class (in this case another Provider)?

like image 570
updatestage Avatar asked Sep 03 '19 06:09

updatestage


People also ask

What is multi provider in Flutter?

MultiProvider class Null safetyA provider that merges multiple providers into a single linear widget tree. It is used to improve readability and reduce boilerplate code of having to nest multiple layers of providers.

What is proxy provider Flutter?

A provider that builds a value based on other providers. The exposed value is built through either create or update , then passed to InheritedProvider.


2 Answers

Thanks for your answer. In the meanwhile, I solved it with another solution:

In the main.dart file I now use ChangeNotifierProxyProvider instead of ChangeNotifierProvider for the depending provider:

// main.dart
return MultiProvider(
      providers: [
        ChangeNotifierProvider(builder: (_) => Auth()),
        ChangeNotifierProxyProvider<Auth, Messages>(
          builder: (context, auth, previousMessages) => Messages(auth),
          initialBuilder: (BuildContext context) => Messages(null),
        ),
      ],
      child: MaterialApp(
        ...
      ),
    );

Now the Messages provider will be rebuilt when the login state changes and gets passed the Auth Provider:

class Messages extends ChangeNotifier {
    final Auth _authProvider;

    List<Message> _messages = [];
    List<Message> get messages => _messages;

    Messages(this._authProvider) {
        if (this._authProvider != null) {
            if (_authProvider.loggedIn) fetchMessages();
        }
    }

    ...
}
like image 76
updatestage Avatar answered Oct 16 '22 14:10

updatestage


From version >=4.0.0, we need to do this a little differently from what @updatestage has answered.

return MultiProvider(
  providers: [
    ChangeNotifierProvider(builder: (_) => Auth()),
    ChangeNotifierProxyProvider<Auth, Messages>(
      update: (context, auth, previousMessages) => Messages(auth),
      create: (BuildContext context) => Messages(null),
    ),
  ],
  child: MaterialApp(
    ...
  ),
);
like image 41
AnandShanbhag Avatar answered Oct 16 '22 15:10

AnandShanbhag