I have a List of players:
final List<String> _players = [];
which I populate from the UI using:
addPlayerToList() {
if (playerNameController.text.isNotEmpty && _players.length < 3) {
setState(() {
_players.add(playerNameController.text);
});
}
}
from which I want to pick random two players:
var randomPair = '';
generatePair<T>(List<T> players, int count) {
randomPair = (players.toList()..shuffle()).take(count).toString();
}
So far so good, but the problems start when I'm trying to split the result of the above operation which is (Player1, Player4)
into two separate strings in order to display them nicely in the UI i.e. modal with some flashy Player1 vs. Player2
:
getNames() {
var playerNames = randomPair.split(',');
for (int i = 0; i < playerNames.length; i ) {
playerNames.add(playerNames[i]);
}
return playerNames;
}
What am I doing wrong?
CodePudding user response:
Instead of generating a String, which contains the pair, for then split the string, we should instead just write the code so it returns a list with two random selected players.
So something like this:
void main() {
List<String> players = ['Player A', 'Player B', 'Player C', 'Player D'];
List<String> selectedPlayers = selectRandomAmount(players, 2);
print(selectedPlayers); // [Player C, Player A]
}
List<T> selectRandomAmount<T>(List<T> players, int count) =>
[...(players.toList()..shuffle()).take(count)];