I had an enlightened moment looking a long stretch of ugly code and realized I should make a class and make a lot of the ugly code into methods for that class to clean everything up.
The problem I am trying to think through is that I want the class to be re-usable for my two main use cases.
Firestore query with .snapshots()
Firestore query with .getDocuments()
All the methods of the class I want to make will be manipulating and calculating based off a bunch of documents.
Since .snapshots() returns a QuerySnapshot and .getDocuments() returns a Future<QuerySnapshot> will I have any issues if I make the main data type of the class a QuerySnapshot?
class Items {
final QuerySnapshot data;
Items(this.data);
//methods
int countDocuments() {
return data.docs.length;
}
//more methods go below
}
Could I use this class with either a .snapshots() or a .getDocuments() firestore call? If not what would be the best approach for building out this class to work with both?
Update:
So I officially built the class and it works when I do this call:
(StreamBuilder(
stream: db
.collection('PackList')
.doc(packID)
.collection('PackContents')
.orderBy('itemName')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
PackGear thisPack = PackGear(snapshot, packID);
....
But it does not work if I am not calling a stream. I am stuck with getting the snapshot to pass:
AsyncSnapshot<QuerySnapshot> snapshot = db
.collection('PackList')
.doc(pack)
.collection('PackContents')
.orderBy('itemName')
.get();
PackGear(snapshot, pack);
When I try to use the class with the .get() instead of the stream I get this error:
A value of type 'Future<QuerySnapshot<Map<String, dynamic>>>' can't be assigned to a variable of type 'AsyncSnapshot<QuerySnapshot<Object?>>'. Try changing the type of the variable, or casting the right-hand type to 'AsyncSnapshot<QuerySnapshot<Object?>>
I tried casting and that did not work.