How to get value inside list without index?

Viewed 2186

I am creating an app using flutter and dart.

I have a list of objects with the name parameter, and I want to check if the user input is equal to any of the names of objects inside list.

Simply I want to take input from a user and switch if one of the objects inside a list has this value to add it in a list

I have searched a lot but with nothing.

void main() {
  Data data = Data();

  String name = 'Messi';
//I want to switch if name equals any name inside players list without index
}

class Data {

  List<Player> players = [

    Player(
    name: 'Messi',
    ),

    Player(
    name: 'Mohamed',
    ),

  ];

}
2 Answers

If you want to get a filtered list from the list you have, you can do this:

players.where((player) => player.name == userInput).toList();

If you just want the first occurrence, you can do this:

players.firstWhere((player) => player.name == userInput);

You can use the method forEach from the lists.

It basically works like this:

players.forEach ((player) {
   if(player.name == name){
     your code...
   }
 });

Hope this helps!

Related