Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4066

Unable to Fetch Firestore Data Using Nested Collections in Flutter

$
0
0

I'm having trouble fetching data from Firestore using nested collections in a Flutter application. The data is structured as follows:

users/{userId}/tests/{testType}/test_set/{testSetId}

Image of data in firestore:firestore datafirestore data2

I am trying to retrieve all documents within the test_set collection for a specific test type. However, my queries are returning empty results, even though the data exists in Firestore. The Firestore security rules are set to allow read and write access for authenticated users.

users└── {userId}└── tests└── {testType}└── test_set└── {testSetId}├── correct_answers: int├── total_questions: int└── timestamp: Timestamp
rules_version = '2';service cloud.firestore {  match /databases/{database}/documents {    match /{document=**} {      allow read, write: if request.auth != null;    }  }}

Here is the relevant part of my Flutter code where I'm trying to fetch the data:

Future<List<Map<String, dynamic>>> _fetchTestResults() async {    final user = FirebaseAuth.instance.currentUser;    if (user == null) return [];    print("UUID = " + user.uid);    // Build the reference step by step and print debug information    final usersRef = FirebaseFirestore.instance.collection('users');    print('Users reference path: ${usersRef.path}');    final userDocRef = usersRef.doc(user.uid);    print('User document reference path: ${userDocRef.path}');    final testsCollectionRef = userDocRef.collection('/tests/');    print('Tests collection reference path: ${testsCollectionRef.path}');    // final testResultsRef =    //     testsCollectionRef.doc(testType).collection('test_set');    // print('Test results reference path: ${testResultsRef.path}');    // Fetch data    final snapshot = await testsCollectionRef.get();    print('Snapshot: ${snapshot.docs.length} documents');    if (snapshot.docs.isEmpty) {      print("Snapshot empty");      return [];    }    return snapshot.docs.map((doc) {      final data = doc.data();      print('Document ID: ${doc.id}, Data: $data');      return {'test_id': doc.id,'data': data,'timestamp': data['timestamp'] as Timestamp,'correct_answers': data['correct_answers'] as int,      };    }).toList();  }

Logs showing 0 snapshots image belowImage of logs showing 0 data in snapshot

But if instead I print the userRef.get() as snap shot I get output as below

final snapshot = await usersRef.get();    print('Snapshot: ${snapshot.docs.length} documents');

user ref output


Viewing all articles
Browse latest Browse all 4066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>