I want to show "No posts" text when database don't have any posts (length = 0) (Database's post type is list)
When I use this code, it shows error
Error here :
════════ Exception caught by widgets library ═══════════════════════════════════
Class '_JsonQuerySnapshot' has no instance method '[]'.
Receiver: Instance of '_JsonQuerySnapshot'
Tried calling: []("posts")
My code here:
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection("users")
// .orderBy('datePublished', descending: true)
.snapshots(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data['posts'].length != 0) {
return showWidget();
} else {
return Container(
child: Center(child: Text("No posts")),
);
}
} else {
return const Center(
child: CircularProgressIndicator(color: Colors.red),
);
}
});
CodePudding user response:
you're trying to get snapshots for a whole collection with :
FirebaseFirestore.instance
.collection("users")
.snapshots(),
this will return a QuerySnapshot
which will contain the docs
list, so you need to iterate over them to check:
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("users")
// .orderBy('datePublished', descending: true)
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
final isCollectionEmpty = snapshot.data!.docs.isEmpty;
final DocumentsWhichContainsPosts = snapshot.data!.docs.where((doc) => (doc.data() as Map<String, dynamic>)["posts"].isNotEmpty);
if (DocumentsWhichContainsPosts.isNotEmpty) {
return showWidget();
} else {
return Container(
child: Center(child: Text("No posts")),
);
}
} else {
return const Center(
child: CircularProgressIndicator(color: Colors.red),
);
}
});