How to have multiple stream providers of the same datatype in flutter?

Issue

I want to have two stream providers of type QuerySnapshot from two different Firebase collections. When I tried just making two stream providers of the same value, one of the stream providers just overrided the other one. Is it possible to somehow differentiate between two stream providers of the same data type? Here is my current code for the two providers:

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider.value(value: FirestoreHelper.getClassCollectionReference(context).snapshots()),
        StreamProvider.value(value: FirestoreHelper.getTaskCollectionReference(context).snapshots()),
      ],
      

Solution

Yes, there is always a way. What you can do is make a custom class or model class for any of your Query and then map the snapshot coming from that query with the custom class.

class MySnap {
  final QuerySnapshot snapshot;
  MySnap(this.snapshot);
}

Change any of Your provider to this

StreamProvider.value(value:FirestoreHelper.getClassCollectionReference(context).snapshots().map<MySnap>((snap) => MySnap(snap)),

For accessing the data use:

var mysnap = Provider.of<MySnap>(context);
var data =  mysnap.snapshot;///This is your querysnapshot

Answered By – Jagraj Singh

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *