class Player{
final String playerName;
final int playerValue;
Player({this.playerName,this.playerValue});
final List <Player> playersList = [
Player(playerName: 'player1', playerValue: 20),
Player(playerName: 'player2', playerValue: 20),
Player(playerName: 'player1', playerValue: 30),
Player(playerName: 'player3', playerValue: 50),
Player(playerName: 'player5', playerValue: 60),
];
player1 = (playersList..shuffle()).first;
player2 = (playersList..shuffle()).last;
while (player1.playerName == player2.playerName || player1.playerValue == player2.playerVaue) {
player2 = (playersList..shuffle()).last;
}
So this is what I'm trying to do: I want to manually create a list of Players as shown above and want to randomly assign one of those players to player1 and player2 just in case both of them turn out having the same value or name, I want to randomly select the player so that we can compare their values. I'm not really able to figure out how to formulate it in code. Also, I want to send the playerName and playerValue to another class where I'll have them displayed in a stateful widget. As you can see I'm just starting out with Flutter so really any help would be greatly appreciated!
This works...
final List<Player> playersList = [
Player(playerName: 'player1', playerValue: 20),
Player(playerName: 'player2', playerValue: 20),
Player(playerName: 'player1', playerValue: 30),
Player(playerName: 'player3', playerValue: 50),
Player(playerName: 'player5', playerValue: 60),
];
playersList.shuffle();
var player1 = playersList.first;
var player2 = player1;
while (player1.playerName == player2.playerName) {
playersList.shuffle();
player2 = playersList.first;
}
print(player1);
print(player2);
UPDATE: Wrap it in a method in the Player class
class Player {
final String playerName;
final int playerValue;
Player({this.playerName, this.playerValue});
static List<Player> pairPlayers() {
final List<Player> playersList = [
Player(playerName: 'player1', playerValue: 20),
Player(playerName: 'player2', playerValue: 20),
Player(playerName: 'player1', playerValue: 30),
Player(playerName: 'player3', playerValue: 50),
Player(playerName: 'player5', playerValue: 60),
];
playersList.shuffle();
var player1 = playersList.first;
var player2 = player1;
while (player1.playerName == player2.playerName) {
playersList.shuffle();
player2 = playersList.first;
}
return [player1, player2];
}
@override
String toString() {
return playerName;
}
}
Then anytime you want to pair players use
Players.pairPlayers();