9

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 the print statement output:

flutter: Values from db: Instance of 'DocumentSnapshot'.

I also tried the 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); }); } }); 

The output here is only the documentID name...

So, how could I get the field values from Firestore?

5
  • 3
    try using ds["fieldname"] or ds.fieldname Commented Jul 18, 2019 at 12:03
  • What fields you have? means what model you have, can you tell me? Commented Jul 18, 2019 at 12:28
  • @MuhammadNoman Test(Collection) -> test(document) -> stackTest: value(field-ref and value) Commented Jul 18, 2019 at 12:33
  • @ParthPatel thanks, it works with your method. :) Commented Jul 18, 2019 at 12:35
  • @RusbenWladiskoz It's my pleasure. You can Flag and Upvote my comment :) Commented Jul 18, 2019 at 12:37

5 Answers 5

7

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"); } }); 
Sign up to request clarification or add additional context in comments.

Comments

5

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']); } } ) 

Comments

5

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']; } }); 

Comments

1

I have a list of users in a Firestore database and I need to extract the userName information:

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 authenticated 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

Comments

0

There are 2 ways:

1. StreamBuilder

When you want to listen to changes constantly, and want the data to get updated without hot reload/restart

2. FutureBuilder

When you want to get the document only once and have no requirement of listening constantly to the change of the document.


StreamBuilder

1. Multiple Documents

 @override Widget build(BuildContext context) { return Scaffold( body: Center( child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore .instance. .collection('users') // πŸ‘ˆ Your desired collection name here .snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return const Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return const Text("Loading"); } return ListView( children: snapshot.data!.docs.map((DocumentSnapshot document) { Map<String, dynamic> data = document.data()! as Map<String, dynamic>; return ListTile( title: Text(data['fullName']), // πŸ‘ˆ Your valid data here ); }).toList()); }, ), ), ); } 

2. Single Document

 @override Widget build(BuildContext context) { return Scaffold( body: Center( child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>( stream: FirebaseFirestore .instance .collection('users') .doc(FirebaseAuth.instance.currentUser!.uid) // πŸ‘ˆ Your document id change accordingly .snapshots(), builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) { if (snapshot.hasError) { return const Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return const Text("Loading"); } Map<String, dynamic> data = snapshot.data!.data()! as Map<String, dynamic>; return Text(data['fullName']); // πŸ‘ˆ your valid data here }, ), ), ); } 

FutureBuilder

1. Multiple Documents

@override Widget build(BuildContext context) { return Scaffold( body: Center( child: FutureBuilder<QuerySnapshot>( future: FirebaseFirestore .instance .collection('users') // πŸ‘ˆ Your collection name here .get(), builder: (_, snapshot) { if (snapshot.hasError) return Text('Error = ${snapshot.error}'); if (snapshot.connectionState == ConnectionState.waiting) { return const Text("Loading"); } return ListView( children: snapshot.data!.docs.map((DocumentSnapshot document) { Map<String, dynamic> data = document.data()! as Map<String, dynamic>; return ListTile( title: Text(data['avatar']), // πŸ‘ˆ Your valid data here ); }).toList()); }, )), ); } 

2. Single Document

 @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>( future: FirebaseFirestore.instance .collection('users') .doc(FirebaseAuth.instance.currentUser!.uid) // πŸ‘ˆ Your document id change accordingly .get(), builder: (_, snapshot) { if (snapshot.hasError) return Text('Error = ${snapshot.error}'); if (snapshot.connectionState == ConnectionState.waiting) { return const Text("Loading"); } Map<String, dynamic> data = snapshot.data!.data()!; return Text(data['fullName']); //πŸ‘ˆ Your valid data here }, )), ); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.