MinHo Kim
MinHo Kim

Reputation: 41

Flutter : How can i get collection from document with cloud_firestore?

I can get all documents from collection but, don't know how to get collection from each document.

My Database structure is like collection -> document -> collection(with field) -> document -> field.

with blow code, only i can get field information of 1st document, not collection.

How can i access 2nd collection from each 1st document.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:location/location.dart';

StreamSubscription<QuerySnapshot> subscription;
List<DocumentSnapshot> wallpapersList;


...


class MapPageState extends State<MapPage> {

  final CollectionReference collectionReference =
  Firestore.instance.collection("users");



  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    print(wallpapersList);

    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        wallpapersList = datasnapshot.documents;

      });
    });
}

...

Upvotes: 3

Views: 3760

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

You can get the subcollection from a DocumentSnapshot via document.reference.collection("subcollection").

So for example:

wallpapersList.reference.collection("subcollection")

Upvotes: 6

Enzo Lizama
Enzo Lizama

Reputation: 1315

Build a function to get all your documents and return a QuerySnapshot

Future<QuerySnapshot> getDocuments() async {
    return await Firestore.instance
        .collection('collectionName')
        .document(referenceFromADocument)
        .collection('otherCollectionName')
        .getDocuments();
  }

In your widget you can access this via FutureBuilder

return FutureBuilder<QuerySnapshot>(
      future: _viewModel.getDocuments(),
      builder: (context, snapshot) {
        snapshot.data.documents.map((document) {
          if(snapshot.hasData){
            print(document.toString());
            /// Here you can return a Text widget
          }          
        }).toList()),
      }
);

Hope this could help

Upvotes: 4

Related Questions