shuffle 方法

void shuffle(
  1. [Random? random]
)
覆盖

随机洗牌此列表的元素。

final numbers = <int>[1, 2, 3, 4, 5];
numbers.shuffle();
print(numbers); // [1, 3, 4, 5, 2] OR some other random result.

实现

void shuffle([Random? random]) {
  random ??= Random();

  int length = this.length;
  while (length > 1) {
    int pos = random.nextInt(length);
    length -= 1;
    var tmp = this[length];
    this[length] = this[pos];
    this[pos] = tmp;
  }
}