skip to Main Content

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


  1. `if(snapshot.hasData && snapshot.data.isEmpty)` - this case can be worked.
    
    Login or Signup to reply.
  2. 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()),
                );
              },
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  3. Currently, you are just checking if the data exists 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
    }
    

    A cleaner way of doing if-else in dart:

    snapshot2.hasData && snapshot2.data == null
       ? widget1
       : widget2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search