How to use a provider inside of another provider in Flutter

前端 未结 4 970
遇见更好的自我
遇见更好的自我 2021-02-14 08:21

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 create

4条回答
  •  攒了一身酷
    2021-02-14 08:56

    It's simple: the first Provider provides an instance of a class, for example: LoginManager. The other Provides MessageFetcher. In MessageFetcher, whatever method you have, just add the Context parameter to it and call it by providing a fresh context.

    Perhaps your code could look something like this:

    MessageFetcher messageFetcher = Provider.of>(context).value;
    String message = await messageFetcher.fetchMessage(context);
    

    And in MessageFetcher you can have:

    class MessageFetcher {
      Future fetchMessage(BuildContext context) {
        LoginManager loginManager = Provider.of>(context).value;
        loginManager.ensureLoggedIn();
        ///...
      }
    }
    

提交回复
热议问题