Flutter Firestore Read specific field from specific document via stream function

375

If you already have the document id, then just do:

static Future<DocumentSnapshot> readUserProfileData({
    required String docId,
    required String field,
  }) async {
    var ref = _mainCollection.doc(docId).get().then((snapshot) {
        print(snapshot);
        print(snapshot.data()[field]);
    });
  }

You don't need to use forEach since you are only retrieving one document and get() will have a return type Future<DocumentSnapshot>

Share:
375
RedsVision
Author by

RedsVision

Updated on December 30, 2022

Comments

  • RedsVision
    RedsVision over 1 year

    basically im struggling to create a function in my database.dart where i can call this function to display a specfic field in a specific document.

    Example, i want to use Database.readUserProfileData('Profile', 'surname') to display the string/alt to a widget.

    static Future<QuerySnapshot> readUserProfileData({
        required String docId,
        required String field,
      }) async {
        var ref = _mainCollection.get().then((querySnapshot) {
          querySnapshot.docs.forEach((result) {
            Object? data = result.data();
            print(data);
          });
        });
      }
    

    Here is my database.dart

    (please ignore the UpdateItem function as i have not configured it properly as i copied this from a template, or maybe update it for me lol sorry ;))

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/cupertino.dart';
    
    final FirebaseFirestore _firestore = FirebaseFirestore.instance;
    
    /* ------------------ Database Reference - Main Collection ------------------ */
    final CollectionReference _mainCollection = _firestore.collection('_TestFB');
    
    class Database {
      static String? userUid;
    
      /* -------------------------- Create User Database -------------------------- */
      static Future<void> createUserDataFile({
        required String uid,
        required String surname,
        required int mobile,
      }) async {
        DocumentReference documentReferencer =
            _mainCollection.doc('UserData').collection(uid).doc('Profile');
    
        Map<String, dynamic> data = <String, dynamic>{
          "surname": surname,
          "mobile": mobile,
        };
    
        _mainCollection
            .doc('UserData')
            .collection(uid)
            .limit(1)
            .get()
            .then((snapshot) async {
          if (snapshot.size == 1) {
            print("**User Profile Exists");
          } else {
            await documentReferencer
                .set(data)
                .whenComplete(() => print("**New Profile Created for - " + uid))
                .catchError((e) => print(e));
          }
        });
      }
    
      /* ------------------------- Read User Profile Data ------------------------- */
      static Future<QuerySnapshot> readUserProfileData({
        required String docId,
        required String field,
      }) async {
        var ref = _mainCollection.get().then((querySnapshot) {
          querySnapshot.docs.forEach((result) {
            Object? data = result.data();
            print(data);
          });
        });
      }
    

    Thanks in Advance

  • bsplosion
    bsplosion over 2 years
    It's unfortunate that this doesn't really answer the question of how to read a specific field from a specific document on Firestore, but rather answers the question of "after having read and retrieved all fields from a specific document, how to I return a specific field value".
  • Peter Haddad
    Peter Haddad over 2 years
    @bsplosion This answers the question that OP was asking. The method in the answer, is the one OP is already using. They wanted to get a specific field and they were already reading all the documents in a collection while having access to the docId. So, all I did is show OP how to access the specific field if you already have the document id which is exactly what OP wanted.
  • Peter Haddad
    Peter Haddad over 2 years
    @bsplosion (if I understood what you mean) you cannot read a specific field from a document. The only way if you have the document id, is to retrieve all the fields inside the documents, then display what you want. But, if you have 10 fields in one document, you cannot read one field and not read the other 9 fields, you can only read on the document level (meaning all fields will be retrieved) or a collection level. This is how firebase works in all platforms..
  • bsplosion
    bsplosion over 2 years
    Certainly agreed there, and it's technically not even possible to select just one field directly from Firestore via client methods presently. I was more remarking that it's unfortunate the question is worded and tagged the way it is, which implies some relationship to Flutter/Firestore/any particular platforms. As-answered, the question has almost nothing to do with its tags. The OP just didn't know how to access an object property dynamically.
  • Peter Haddad
    Peter Haddad over 2 years
    @bsplosion Oh I understand, well you can just edit it in this case. I have removed the android tag since it's not really used here. But anyway the question only has 116 views since 5 month ago, so I don't think a lot of people are finding this question/answer when performing a google search, but nevertheless feel free to edit and I can approve the edit if all is fine! Unfortunately there are many questions that are worded in a confusing way :/