here I am getting all the following ids and storing in list of string
List<String> followinguserid = [];
Future<QuerySnapshot> _timelinepoststream;
getAllFollowingId() async {
String currentuserid = await UserSecureStorage.getUserId();
print(currentuserid);
await followingRef
.doc(currentuserid)
.collection('userFollowing')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) {
followinguserid.add(element.id);
});
});
}
in init function i am making the query
@override
void initState() {
// TODO: implement initState
super.initState();
getAllFollowingId();
_timelinepoststream = FirebaseFirestore.instance
.collection('posts')
.where('UserIds', arrayContainsAny: [
...followinguserid
]).get();
}
here i am using future builder and passing the future
@override
Widget build(BuildContext context) {
var width = MediaQuery.of(context).size.height;
var height = SizeConfig.getHeight(context);
return FutureBuilder(
future: _timelinepoststream,
builder: (context, snapshot) {
List<DocumentSnapshot> documents;
if (snapshot.connectionState == ConnectionState.done) {
print(snapshot.data.docs);
documents = snapshot.data.docs;
return Text("sample");
}})}
CodePudding user response:
Since getAllFollowingId
is an async
method, you need to use await
when calling it:
await getAllFollowingId();
Without await
your database query runs before the followinguserid
has been populated, which explains the error message.
If you can't use await
, you can also use a then()
callback:
getAllFollowingId().then(() {
_timelinepoststream = FirebaseFirestore.instance
.collection('posts')
.where('UserIds', arrayContainsAny: [
...followinguserid
]).get();
})