0

I have a method that fetches all the users from the firebase database, and then I store all the users inside a list. let's say my list is:

    user1 = User(
    id: 1
    name: "john"
    car: false
   )

    user2 = User(
    id: 2
    name: "kim"
    car: true
    )

 userList = [user1,user2]

How do I get the id of the user based on the name for example?

2 Answers 2

2

One of the simplest ways is using forEach(), which needs a function as argument:

class User{
  final int id;
  final String name;
  final bool car;

  User({this.id, this.name, this.car});
}

void main() {
  User user1 = User(
    id: 1, 
    name: "john", 
    car: false
  );

  User user2 = User(
    id: 2, 
    name: "kim", 
    car: true
  );

  List<User> userList = [user1,user2];

  userList.forEach((user){
    if(user.name == "john")
      print("ID: ${user.id}");
  });
}

But you have more options, look up this list Top 10 Array utility methods you should know (Dart)

This way you can get all the johns:

List<User> johns = userList.where((user) => user.name == "jhon");
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the where on a list to filter it out. Example:

 var userList = [user1,user2];

 var kimList =  userList.where((f) => f.name == 'kim').toList();

 kimList.forEach((u) => print( '${u.name } - ${u.id}')); // will contain all the users where name is kim

References

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.