'Can same stream(QuerySnapshot) be used with multiple StreamBuilder on different pages? ---Flutter

Maybe it's a newbie question, but I would like to know is it possible to use same stream(Stream) to build the UI of two pages. Let's take an example: if there are two pages which should display the same list of data(say username and address) which is read from firebase. Can this be done by reading the data from firestore once and using same stream with streambuilder on each page?

I'm able to display the list(using streambuilder and Listview.builder) on first page but when I navigate to second page and use same stream(not reading this from firebase again but using the same stream which was read for first page) it doesn't work. I tried StreamController.broadcast(); also but no luck.

Can anyone help here?



Solution 1:[1]

It happens because the stream has listeners already (the first StreamBuilder). Instead, you could use some sort of state management (it will vary on the application complexity) and provide the stream.

Let's say you are listening to a Stream<List<int>> (to make an easy example). If you used the flutter_bloc package, you could have a BLoC with a StreamSubscription which would be the only listener to that Stream and then you could consume the data from the BLoC all around your app.
It may be kind of confusing if you have little knowledge about Reactive Programming and Dart Streams (I must admit, I've lost many hours trying to understand it - yet it is simpler than it seams!), but the fluter_bloc package has a great documentation. You can find an example in which it uses the StreamSubscription with Firestore!

If you have any doubt with the package or any of the examples, feel free to post an issue in the GitHub repository!

Solution 2:[2]

yes, I just solved the problem. Make a class with static method which return stream. use this stream in your StreamBuilder widget. and use this widget on any page :)

example:

class FirebaseStream {
  // ...
  static Stream<DocumentSnapshot<Model>> myStreamMethod() {
    return _collectionRef.snapshots();
  }
  // _collectionRef is collection reference with withConverter<Model>()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mddg
Solution 2 Rajendra A Verma