下面的两个示例向您展示了如何在 Dart 中反转和打乱给定列表。
反转 Dart 列表
编码:
// main.dart
void main() {
final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List listTwo = ['a', 'b', 'c', 'd'];
final List reversedListOne = listOne.reversed.toList();
print(reversedListOne);
final List reversedListTwo = listTwo.reversed.toList();
print(reversedListTwo);
}
输出:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[d, c, b, a]
对dart列表洗牌
我们可以使用shuffle()方法随机打乱列表。请注意,此方法将更改原始列表。
例子:
// main.dart
void main() {
final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List listTwo = ['a', 'b', 'c', 'd'];
listOne.shuffle();
listTwo.shuffle();
print(listOne);
print(listTwo);
}
输出:
[5, 1, 9, 4, 2, 3, 7, 8, 6]
[b, c, a, d]
由于随机性,每次执行代码时很可能会收到不同的输出。