I have a collection A in cloud Firestore which is empty for now but later it will be filled, I want to display a widget like Text("No Data") when there is no data in it.
This is my code
class Green extends StatefulWidget {
const Green({Key? key}) : super(key: key);
@override
State<Green> createState() => _GreenState();
}
class _GreenState extends State<Green> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection(uid)
.where("gatename", isEqualTo: "A")
.snapshots(),
builder: (_, snapshot2) {
if (snapshot2.hasError) return Text('Error = ${snapshot2.error}');
if (snapshot2.hasData) {
final ds = snapshot2.data!.docs;
return Padding(
padding: const EdgeInsets.all(38.0),
child: Container(
height: 600,
child: ListView.builder(
itemCount: ds.length,
itemBuilder: (_, i) {
final d = ds[i].data();
return ListTile(
title: Text(d["time"].toString()),
leading: Text(d["gatename"].toString()),
);
},
),
),
);
}
return const Center(child: CircularProgressIndicator());
},
));
}
}
I have used else if (snapshot.data!.docs.isEmpty){}
but it is still showing white screen.
3
Answers
You can check the data you’ve received
Currently, you are just checking if the data exists and not if it’s empty.
You should also check if the data is empty:
A cleaner way of doing if-else in dart: