Is there a way to display the fields of a Firestore Document with conditions?

Viewed 50

I am building a Flutter - Firebase app and I am stuck with advanced display of a Firestore document.

I get the document like so:

   Stream<DocumentSnapshot> get theData{
    return dataCollection.doc(documentId).snapshots();
  }

I then consume the data in a Streambuilder like so:

StreamBuilder<DocumentSnapshot>(stream: theData)

I then get the data like this:

Map<String, dynamic> data= snapshot.data?.data() as Map<String, dynamic>;

To display all fields in the document, I would do something like this:

            Column(
                children: [
                  for (var item in data.keys)
                    Padding(
                      padding: const EdgeInsets.all(5),
                      child: ListTile(
                        tileColor: Colors.grey[300],
                        title: Text(
                           item,
                            style: TextStyle(
                               fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                          subtitle: Text('${data[item]}'),
                       ),
                     )
                 ],
               )

However, I would like to NOT display some fields based on the keys I specify.

Also, some fields are arrays of image links and would like to render those links as images.

1 Answers

Try this:

Column(
   children: [
      for (var item in data.keys)
         if(condition) Padding(
            padding: const EdgeInsets.all(5),
            child: ListTile(
               tileColor: Colors.grey[300],
               title: Text(
                  item,
                  style: TextStyle(
                     fontWeight: FontWeight.bold, fontSize: 20),
                  ),
              subtitle: Text('${data[item]}'),
           ),
        )
    ],
);

And for image links:

Image.network(
   link_in_here,
);

How to display all images:

final Map<String, dynamic> data = {
    "link1": "https://cdn.pixabay.com/photo/2022/09/07/10/01/landscape-7438429_960_720.jpg",
    "not-a-link": "Hello",
    "link2": "https://cdn.pixabay.com/photo/2014/11/10/13/18/goose-525420_960_720.jpg",
    "link3": "https://cdn.pixabay.com/photo/2018/08/23/07/35/thunderstorm-3625405_960_720.jpg",
  };

  
 Column(
   children: [
      for (var item in data.keys)
         if(Uri.parse(data[item]).isAbsolute) // Check if item is a valid url
             Image.network(data[item])       
    ],
);
Related