如何在Flutter中使用另一个提供程序内部的提供程序 [英] How to use a provider inside of another provider in Flutter

查看:83
本文介绍了如何在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.

所以我为用户和登录管理创建了一个 Provider ,为用户看到的消息创建了一个。

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

现在,我想在用户登录时一次获取消息。在小部件中,我可以通过 Provider.of< T>(上下文)访问提供商,我想这是 Singleton 的一种。但是,如何从另一个类(在本例中为另一个提供者)访问它呢?

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

推荐答案

感谢您的回答。我同时解决了另一个解决方案:在main.dart文件中,我现在使用 ChangeNotifierProxyProvider 代替 ChangeNotifierProvider 提供者:

Thanks for your answer. I meanwhiles solved it witch another solution: In the main.dart file I now use ChangeNotifierProxyProvider instead of ChangeNotifierProvider for the dependig 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();
        }
    }

    ...
}

这篇关于如何在Flutter中使用另一个提供程序内部的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆