'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()),
],
Solution 1:[1]
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
Solution 2:[2]
- create your data type as an abstract class, for example called Country
- create 2 classes and they inherit ChangeNotifier with the mixin from the country class
- 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.
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 | Jagraj Singh |
| Solution 2 |
