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

查看:22
本文介绍了如何在 Flutter 中使用另一个提供者内部的提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有 authentication service 的应用程序,该应用程序具有不同的权限和功能(例如消息),具体取决于用户角色.

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.

现在,我想在用户登录时(一次)获取消息.在 Widgets 中,我可以通过 Provider.of<T>(context),我猜这是一种 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)?

推荐答案

感谢您的回答.同时,我用另一种解决方案解决了它:

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

main.dart 文件中,我现在使用 ChangeNotifierProxyProvider 而不是 ChangeNotifierProvider 作为依赖提供者:

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

    ...
}

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

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