Home > Back-end >  How to fetch specific data from querysnapshot in flutter
How to fetch specific data from querysnapshot in flutter

Time:06-14

I am trying for so long to fetch specific data out of firebase collection using Futurebuilder querysnapshot. I've made a class for querysnapshot which is:

class Crud {
  final currentUser = FirebaseAuth.instance.currentUser!.uid;

  Future<QuerySnapshot> getData() async {
    return await FirebaseFirestore.instance
        .collection("userpreferences")
        .where(FirebaseAuth.instance.currentUser!.uid)
        .get();
  }
}

This is my futurebuilder.

FutureBuilder<QuerySnapshot>(
            future: crud.getData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final querySnaphost = snapshot.data; // Get query snapshot
                if (querySnaphost!.docs.isNotEmpty) {
                  print(querySnaphost.docs[0].data());
 // Print is giving correct documents 
// I/flutter (16837): {peopletohangoutwith: Testing it again 
// I/flutter (16837): , agerange: 29 - 49}
                  // Document exists
                  final documentSnapshot = querySnaphost.docs;

I want agerange from this document only to show. I am using Text to show it. If anyone can tell me how can I fetch the data then please do let me know. Thank you

CodePudding user response:

Since you're not specifying what data your document contains when you create the StreamBuilder, you get back an Object when you call data(). You'll need to cast that to a Map<String, dynamic> to then be able to get the individual fields from it:

var data = Map<String,dynamic>.from(querySnaphost.docs[0].data() as Map);
return Text(data["peopletohangoutwith"]);
  • Related