Search code examples
firebasefluttergoogle-cloud-firestore

Get collection from firestore, .map doesn't work (flutter)


I'm using Flutter with firebase for my app.

I started my application by putting all my code in the main. dart I now want to organize my files well but I am facing a problem.

I created a service folder, with a database. dart file in which I made a class to find my items in firestorm

the problem is that I do not pass in the snapshot. docs.map ((doc))

here is my code in database. dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutterfirebase/models/todo_model.dart';

class DatabaseService {
  DatabaseService();

  final CollectionReference itemsCollection =
      FirebaseFirestore.instance.collection("items");

  Stream<List<TodoItem>> get todos {
    return itemsCollection.snapshots().map((QuerySnapshot snapshot) {
      inspect(snapshot.docs);
      return snapshot.docs.map((DocumentSnapshot doc) {
        print('here');
        inspect(doc);
        return TodoItem(text: doc.data()['text'], done: doc.data()['done']);
      });
    });
  }
}

the print(snapshot.docs.length); returns 4. The inspect(snapshot.docs) works, I can see my 4 queryDocumentSnapshot with my id

but the print('here') does not appear, nor the inspect(doc)

can you help me figure out what's going on, please?

here are the versions of the packages

firebase_core: ^1.0.2

cloud_firestore: ^1.0.3

Thanks


Solution

  • I think you should return QuerySnapshot from the stream not DocumentSnapshot, just like this

    Stream<List<TodoItem>> getSomeoneItems() {
      return FirebaseFirestore.instance.collection('items')
        .snapshots()
        .map((qSnap) =>
            qSnap.docs.map((doc) => TodoItem.fromJson(doc.data())).toList());
    }
    

    then you can use this stream in your view inside StreamBuilder widget.