Search code examples
flutterdartflutter-providerdart-asyncriverpod

What is the RiverPod way to Consume a StreamProvider outside of Flutter - Dart only


Working with RiverPod for first time and the Provider concept in general.

Goal: Validate the signed in user has an account info document in my accounts FireStore collection.

My code is based off this flutter/firebase starter architecture referenced on the RiverPod site as an example of how to use RiverPod for state management.

I'm using latest flutter_riverpod package.

My minimized code:

firestore_database.dart - implementing model/service layers away from ui.

Stream<Account> accountStream() => _service.documentStream(
        path: FirestorePath.account(uid),
        builder: (data, documentId) => Account.fromMap(data, uid),
      );

account_setup_service.dart

final accountStreamProvider = StreamProvider.autoDispose((ref) {
  final database = ref.watch(databaseProvider);
  return database != null ? database.accountStream() : const Stream.empty();
});

This is the part I'm stuck on. Everything else checks out. How do I consume the accountStreamProvider outside of Flutter in Dart only context? Again, my goal is to simply evaluate whether the stream is empty or if it contains a document.

Consumer(builder: (context, watch, _) {
      final accountAsyncValue = watch(accountStreamProvider);

      return accountAsyncValue.when(
        // what do I do here to validate that there is an account 
        // info document for the currently authorized user 
        // using the accountStreamProvider?
        // I don't want to return a widget...
        data: (account) => null,
        loading: () => null,
        error: (_, __) => null,
      );
    });

On the RiverPod doc site I've read the "Reading a provider outside of providers using Dart only" reference, however, I'm not sure where to go with it to consume the stream and evaluate data if there is any.


Solution

  • The documentation link you posted shows how to get a StateController from a ProviderContainer.

    It looks like the StateController class has a stream property, so you could listen to that:

    https://pub.dev/documentation/riverpod/latest/riverpod/StateController-class.html

    (I haven't tried that, but that's what I can make out from the docs)