skip to Main Content

I want to get all the document IDs in my firebase and store it in List but I’m only getting one of the documents. Here is my execution

PrtSc

my code

Future saveUserCart(User currentUser) async
{
  List<String> IDs = [];

  Future getDocs() async {
    QuerySnapshot querySnapshot = await FirebaseFirestore.instance
        .collection('users')
        .doc(currentUser.uid)
        .collection("userCart").get();
    for (int i = 0; i < querySnapshot.docs.length; i++) {

      var itemIDs = querySnapshot.docs[i];

      print(itemIDs.id);

      IDs = [itemIDs.id];
    }
    print(IDs);
  }
  getDocs();
}

Fix my problem and learn something

3

Answers


  1. Try IDs.add(itemIDs.id); instead of IDs=[itemIDs.id];

    Login or Signup to reply.
  2. Instead of adding the code in question is creating a new list and assigning it to the last id. When we use add method we can get all ids from the documents.

    Future saveUserCart(User currentUser) async
    {
      List<String> IDs = [];
    
      Future getDocs() async {
        QuerySnapshot querySnapshot = await FirebaseFirestore.instance
            .collection('users')
            .doc(currentUser.uid)
            .collection("userCart").get();
        for (int i = 0; i < querySnapshot.docs.length; i++) {
    
          var itemIDs = querySnapshot.docs[i];
    
          print(itemIDs.id);
    
          IDs.add(itemIDs.id);
        }
        print(IDs);
      }
      getDocs();
    }
    
    Login or Signup to reply.
  3. It’s just Example,

    you can use base on your requirements. For gettings "ID" you don’t need to use for loop, use "map" functions.

     var data = [{'key':'abc', 'id':1},{ 'key': 'xyz', 'id': 2}];
     var mapData = data.map((res) => res['id']);
     print("mapData => ${mapData.toList()}");
    

    Expected Output,

    mapData => [1, 2]
    

    Maybe, it will help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search