How to access some fields of firestore in flutter?

Viewed 7199

Say my document like this: -user_id: -name -address -A lot of heavy data.

I know I could get the entire document and just display the fields that I want, but I nedd to retrieve only name and address from my document, so that my users can save bandwidth.

How can I do this?

PD: this is how I would retrieve the whole document.

return StreamBuilder(
  stream: Firestore.instance
      .collection('users')
      .document(widget.userId.toString())
      .snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.deepOrange),
        ),
      );
    } else {
      return _buildUserTile(context, snapshot.data);
    }
  },
);
1 Answers

Official answer from a Firebase Engineer

Cloud Firestore always reads and returns full documents. There is no way to read a subset of the fields in a document.

You can retrieve the entire document, and then process the DocumentSnapshot to just use the fields you're interested. But this means you're using more bandwidth than needed. If this is a regular occurrence for your app, consider creating a secondary collection where each document contains just the fields you're interested in.

Related