Flutter: List All Firebase Cloud Firestore Documents in a Collection

8/25/2020 5:20:14 PM

The following will list all of the documents in a Firestore collection. Be sure to initialize Firebase in your main.dart file. You will need to mark you main() function as async.

*Update main.dart main() function as async and add the 2 lines below at the top.

import 'package:firebase_core/firebase_core.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  
  ....
}
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class TestApp extends StatelessWidget {
  final firestoreInstance = FirebaseFirestore.instance;

  Future getCloudFirestoreUsers() async {
    print("getCloudFirestore");

    //assumes you have a collection called "users"
    firestoreInstance.collection("users").get().then((querySnapshot) {
      //print(querySnapshot);
      print("users: results: length: " + querySnapshot.docs.length.toString());
      querySnapshot.docs.forEach((value) {
        print("users: results: value");
        print(value.data());
      });
    }).catchError((onError) {
      print("getCloudFirestoreUsers: ERROR");
      print(onError);
    });
  }

  @override
  Widget build(BuildContext context) {
    getCloudFirestoreUsers();

    return new MaterialApp(
        home: Container(
      child: Text("runnning tests"),
    ));
  }
}