简体   繁体   中英

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

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()),
      ],
      

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM