Search code examples
flutterriverpod

Flutter riverpod reacting to a change in the provider's state


I have a StreamProvider that updates the bluetooth status on the device. If the state changes to "unauthorized" I want to call a function in which the user is asked to accept permission. In turn, when the state changes to "ready" I want to display the change on the AppBar. The second option changes the UI and the first option calls a function. Where do I add the logic to be able to check the current state and based on it update the UI or call a function?

I tried to add a check condition to the UI, but this ruins the concept of separating the logic from the UI.


Solution

  • You can define a callback in the ref.listen() function to be able to do something based on the current state. It will look something like this:

    ref.listen(provider, (prev, now) {
      if (now == 'unauthorized') {
        // do something
        Navigator.of(context).pop();    
      }
    });
    

    You can define this function both in the provider and in the build method. In the context of flutter development, this would not be considered bad manners.

    Another option is to host this function in your app's navigation service. Then you have to first get your container, and then add a wiretap:

    final container = ProviderScope.containerOf(context);
    container.listen(
        provider,
        (prev, now) => /* do something */,
      );