'How to get data from firestore document fields in flutter?

I'm trying to test firestore in my flutter-app but I can't really load the data as expected.

This is how I get the data:

 Firestore.instance
        .collection('Test')
        .document('test')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot

      print('Values from db: $ds');
    });

And print-statement output: flutter: Values from db: Instance of 'DocumentSnapshot'.

I also tried following, without success:

Firestore.instance.collection('Test').document('test').get().then((data) {
  // use ds as a snapshot

  if (data.documentID.length > 0) {
    setState(() {
      stackOver = data.documentID;
      print(stackOver);
    });
  }
});

Output here is only the documentID-name..

So, how could I get the field-values from firestore?

Best regards!



Solution 1:[1]

Try this:

final String _collection = 'collectionName';
final Firestore _fireStore = Firestore.instance;

getData() async {
  return await _fireStore.collection(_collection).getDocuments();
}

getData().then((val){
    if(val.documents.length > 0){
        print(val.documents[0].data["field"]);
    }
    else{
        print("Not Found");
    }
});

Solution 2:[2]

I faced a similar problem and solved it this way:

Stream<DocumentSnapshot> provideDocumentFieldStream() {
    return Firestore.instance
        .collection('collection')
        .document('document')
        .snapshots();
}

After that, I used a StreamBuilder to consume the method created above:

StreamBuilder<DocumentSnapshot>(
    stream: provideDocumentFieldStream(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasData) {
            //snapshot -> AsyncSnapshot of DocumentSnapshot
            //snapshot.data -> DocumentSnapshot
            //snapshot.data.data -> Map of fields that you need :)

            Map<String, dynamic> documentFields = snapshot.data.data;
            //TODO Okay, now you can use documentFields (json) as needed

            return Text(documentFields['field_that_i_need']);
        }
    }
)

Solution 3:[3]

Null safe code:

  • One time reading of the data:

    var collection = FirebaseFirestore.instance.collection('users');
    var docSnapshot = await collection.doc('some_id').get();
    if (docSnapshot.exists) {
      Map<String, dynamic> data = docSnapshot.data()!;
    
      // You can then retrieve the value from the Map like this:
      var name = data['name'];
    }
    
  • Continually listening for the data:

    var collection = FirebaseFirestore.instance.collection('users');
    collection.doc('some_id').snapshots().listen((docSnapshot) {
      if (docSnapshot.exists) {
        Map<String, dynamic> data = docSnapshot.data()!;
    
        // You can then retrieve the value from the Map like this:
        var name = data['name'];
      }
    });
    

Solution 4:[4]

I have a list of users in Firestore Database and I need to extract the userName info

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

FirebaseAuth firebaseAuth = FirebaseAuth.instance;

class Database {      
  static String? userName;
  
  static void showDisplayName() async {
    var collection = FirebaseFirestore.instance.collection('users');
    //userUid is the current auth user
    var docSnapshot = await collection.doc(userUid).get();

    Map<String, dynamic> data = docSnapshot.data()!;

    userName = data['displayName'];
  }
}

Then you can call Database.userName to get the string value

Here is my Firestore Example enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Noman
Solution 2 Mark Gavagan
Solution 3
Solution 4 Vladimir Salguero