MAA
MAA

Reputation: 1355

How to check if a document is empty

I have the following empty document:

enter image description here

As I understand it, the document exists, but it's empty. I'm showing the user a list of all document ID, then allowing him to choose the document to display data for. When the user chooses this empty document, an error appears because i called length on null object in my listview. That's fair. I want to show the user an alert dialog informing him that it's empty.

        child: FutureBuilder(
            future: snapshot,
            builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasData) {
                    if(snapshot.data.data.length == 0) {
                      return  AlertDialog(
                        content: Text('Wrong Date', textAlign: TextAlign.center, style: TextStyle(color: Colors.black)),
                        backgroundColor: Colors.redAccent,
                        actions: [Icon(Icons.keyboard_backspace)],
                      );
                  }

This is what I'm going with at the moment. Just checking the length of the document. That does not seem right to me.

Is there any other way of doing this?

Upvotes: 0

Views: 646

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Looking at the API for DocumentSnapshot, the data() method returns a Map of fields. If you want to know if there are no fields, simply ask the Map if its length is 0.

snapshot.data().length == 0

Upvotes: 1

Related Questions