Home > other >  Flutter Populating List<String> using for loop
Flutter Populating List<String> using for loop

Time:12-06

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

CodePudding user response:

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

CodePudding user response:

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();
}

CodePudding user response:

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.

  • Related