I am trying to query a Stream where the document should have 'UretimKurulum' in 'unit' array and the 'date' should be equal or greater than today's date.
While streaming this query I do get the correct results that I want for a brief seconds and then it says 'No Data Available'.
Below is the actual code:
final FirebaseFirestore _db = FirebaseFirestore.instance;
final DateTime _now = DateTime.now();
final String val = 'UretimKurulum';
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot<Object>>(
stream: _db.collection('Schedule').where('date', isGreaterThanOrEqualTo: _now).where('unit', arrayContains: val).snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: LinearProgressIndicator());
} else {
if (!snapshot.hasData) {
return Center(child: Text('No Data Available'));
} else {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
var docSnap = snapshot.data!.docs[index];
return Text(docSnap.id);
},
);
}
}
},
);
}
}
If I try to remove:
if (!snapshot.hasData) {
return Center(child: Text('No Data Available'));
}
I get the following error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building StreamBuilder<QuerySnapshot<Object>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object>, AsyncSnapshot<QuerySnapshot<Object>>>#0508a):
Unexpected null value.
And indeed it was an indexing issue as @blaneyneil and myself stated previously.
The solution was to create a composite collection index from the Firebase Console and index the fields 'todoUnit' as Arrays and 'date' as Ascending.