0

I am pulling data from Firestore as a Stream of a List. I want to take all of the values that are held by the stream and add them to a separate list.

// getting the stream 
Stream<List<AttractionNode>> readAttractionsNodes() =>
        FirebaseFirestore.instance
            .collection("attractions")
            .where("tags", arrayContainsAny: selectedChips)
            .snapshots()
            .map((snapshot) => snapshot.docs
                .map((doc) => AttractionNode.fromJson(doc.data()))
                .toList());

Stream<List<AttractionNode>> _nodes = readAttractionsNodes();

// the list that should hold all nodes from the stream List<AttractionNode> allNodes = [];

_nodes.listen( (listOfNodes) { allNodes = listOfNodes; });

However, it seems that outside of the listen block, allNodes stays empty. How can I fix that?

rk793
  • 1
  • If you want a list of results, is there any reason to not use `get()` instead of `snapshots()`? – Frank van Puffelen Nov 13 '22 at 22:50
  • Is this a `class`, or `StatelessWidget` or something else? – My Car Nov 13 '22 at 22:52
  • @MyCar It is a method. You're using the `.snapshots()` method returns you the `Stream>`. Instead, you can use `.get()` which returns `Future>` – Sahil Sonawane Nov 14 '22 at 10:37
  • @FrankvanPuffelen `.get` would return a Future>. How can I get that to be just a List? – rk793 Nov 15 '22 at 21:56
  • See https://stackoverflow.com/questions/46579358/getting-values-from-future-instances and more from https://www.google.com/search?q=dart+how+to+unwrap+a+future – Frank van Puffelen Nov 15 '22 at 21:59
  • @FrankvanPuffelen Ah I see. Thank you. I'm still wondering why assigning a variable inside the `_nodes.listen` block is not being registered outside. I can print the contents of `listOfNodes` inside the block and manipulate those values, but if I try adding those values to a list that was instantiated outside of the block, it doesn't seem to register. Any ideas? – rk793 Nov 17 '22 at 01:04
  • It's not about *where* you access the variable, but *when* you access it. If you place some logging both inside and outside of the callback, you'll see that it fires in a different order than you probably expect, due to the asynchronous nature of `snapshots()`. – Frank van Puffelen Nov 17 '22 at 01:42

0 Answers0