Alex97
Alex97

Reputation: 466

Firebase getting all docs from a collection

Hello I want to get all docs from a collection in one shot without knowing the docs id's since they are random. Inside each doc I have some data but all I need is the doc itself than I will take the data from each and every one no problem.

I get null every time.

Does anyone know what am I doing wrong?

Thank you in advance.

This is the code :

import 'package:cloud_firestore/cloud_firestore.dart';

Future<Map<String, dynamic>> getVisitedCountries(String ID) async {
  Map<String, dynamic> val = <String, dynamic>{};
  await FirebaseFirestore.instance
      .collection('users')
      .doc(ID)
      .collection('PersonalData')
      .doc(ID)
      .collection('Passport')
      .doc(ID)
      .collection('VisitedCountries')
      .doc()
      .get()
      .then((value) {
    if (value.data().isEmpty) {
      print("User not found");
    } else {
      val = value.data();
    }
  }).catchError((e) {
    print(e);
  });

  return val;
}

This is the structure in the Cloud Firestore enter image description here

Upvotes: 2

Views: 2015

Answers (1)

Alex97
Alex97

Reputation: 466

So for everyone who is having this problem, this is the way to solve it. I solved it thanks to the user : Kantine

Solution : code :

import 'package:cloud_firestore/cloud_firestore.dart';

Future<Iterable> getVisitedCountries(String ID) async {
  // Get data from docs and convert map to List
  QuerySnapshot querySnapshot = await FirebaseFirestore.instance
      .collection('users')
      .doc(ID)
      .collection('PersonalData')
      .doc(ID)
      .collection('Passport')
      .doc(ID)
      .collection('VisitedCountries')
      .get();
  final val = querySnapshot.docs.map((doc) => doc.data());
  return val;
}

I used a query snapshot to get the data and then mapped it.

Upvotes: 1

Related Questions