Home > database >  RiverPod StateProvider returns before code runs in function
RiverPod StateProvider returns before code runs in function

Time:01-03

These print statements don't get printed in order of how the appear. I tried to make this async but it blows up. Essentially I need to listen to a StreamProvider and update a StateProvider based on the stream. Here is my code for the StateProvider.

final unreadNotificationsProvider = StateProvider.autoDispose<bool>((ref) {
  final notifications = ref.watch(notificationsStreamProvider.stream);

  bool unreadNotificationsRead = false;

  notifications.listen((objects) {
    for (var n = 0; n < objects.length; n  ) {
      print("objects: ${objects[n].notification.read}"); <-- Prints second
      if (!objects[n].notification.read) {
        print("GETTING HERE"); // <-- Prints third
        unreadNotificationsRead = true;
      }
    }
  });

  print("unreadNotificationsRead: $unreadNotificationsRead"); // <-- Prints first

  return unreadNotificationsRead;
});

CodePudding user response:

Try to get the value of the stream instead of listening, you dont have to listen the stream because you are already usign ref.watch means the stateProvider will update everytime the notificationsStreamProvider changes.

Replace

final notifications = ref.watch(notificationsStreamProvider.stream);

For

final notifications = ref.watch(notificationsStreamProvider).asData?.value;

Remove notifications.listen and your objects variable will be notifications and before accesing you should ask if notifications == null or notifications.isEmpty

Let me know...

  • Related