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

Viewed 1155

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

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
  1. create your data type as an abstract class, for example called Country
  2. create 2 classes and they inherit ChangeNotifier with the mixin from the country class
  3. use them like:
 Provider<Country1>(
    create: (_) => Country1(),
    child: Provider<Country2>(
    create: (_) => Country2(),
    child: ...,

Now you have 2 data types to use but actually they are the same type from the inheritance.

Related