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.
CodePudding user response:
`if(snapshot.hasData && snapshot.data.isEmpty)` - this case can be worked.
CodePudding user response:
You can check the data you've received
if (snapshot2.hasData) {
if (snapshot2.data==null || snapshot2.data.isEmpty) {
return Text('No Data');
} else {
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()),
);
},
),
),
);
}
}
CodePudding user response:
Currently you are just checking if the data existing and not if it's empty.
You should also check if the data is empty:
if (snapshot2.hasData && snapshot2.data == null) {
return widget1
} else {
return widget2
}
Cleaner way of doing if else in dart:
snapshot2.hasData && snapshot2.data == null
? widget1
: widget2