Home > front end >  Dart How to compare UIDs of two Lists and Generate third List in Flutter
Dart How to compare UIDs of two Lists and Generate third List in Flutter

Time:12-31

I have two lists coming from Firebase, List1 contains all the information of users along with their UIDs. List2 Contains only UIDs of some Users (not all).

I want to get all the details of Users of List2 from List1 by comparing their UIDs

How it would be done?

List1 Contains: uid Name Email Age Etc

List2 Contains: uid (UIDs of users which is also in List 1)

CodePudding user response:

@jamesdlin explained the logic, but I want to show this with an example:

List list1 = [{'name': 'David', 'uid': '1', 'email': '[email protected]'},
               {'name': 'Michael', 'uid': '2', 'email': '[email protected]'},
               {'name': 'Sam', 'uid': '3', 'email': '[email protected]'},
               {'name': 'Oguz', 'uid': '5', 'email': '[email protected]'},
               {'name': 'Esmail', 'uid': '4', 'email': '[email protected]'}];
List list2 = ['1', '2', '3', '4'];
List list3 = [];

void main() {
  //Loop through list 1
  for(Map item in list1){
    //Loop through list2 for every element in list1
    for(String idUser in list2){
      //If the id mathches add item from list1 to list3
      if(idUser == item['uid']){
        list3.add(item);
      }
    }
  }
  print(list3);
}

CodePudding user response:

I found a solution for this.

I was having Two lists List and List respectively.

Below data is homeCtrlr.allUsers means Complete list of all Users and homeCtrlr.requests means a list of All UIDs of users.

final List<UserModel> userDetails = [];

          for (var i = 0; i < homeCtrlr.requests!.length; i  ) {
            for (var j = i; j < homeCtrlr.allUsers!.length; j  ) {
              if (homeCtrlr.requests![i].requestBy ==
                  homeCtrlr.allUsers![j].uid) {
                userDetails.add(homeCtrlr.allUsers![j]);
              }
            }
          }
  • Related