【发布时间】:2020-08-06 10:30:44
【问题描述】:
我正在尝试遍历颜色列表。当循环到达末尾时,我希望它重新启动或转到列表的开头。有人可以帮助我吗?我是 Dart 的新手并且会颤抖。非常感激!!!提前致谢。
List<Color> color = ['Red', 'yellow', 'pink', 'blue'];
所以当它变成 blue 时,我希望它回到 Red 是可能的。请帮忙。
【问题讨论】:
我正在尝试遍历颜色列表。当循环到达末尾时,我希望它重新启动或转到列表的开头。有人可以帮助我吗?我是 Dart 的新手并且会颤抖。非常感激!!!提前致谢。
List<Color> color = ['Red', 'yellow', 'pink', 'blue'];
所以当它变成 blue 时,我希望它回到 Red 是可能的。请帮忙。
【问题讨论】:
作为一个选项:
void main() {
List<String> color = ['Red', 'yellow', 'pink', 'blue'];
for (int i = 0; i < 10; i++) {
print(color[i % color.length]);
}
}
或者你可以像这样为 List 写一个扩展:
void main() {
List<String> color = ['Red', 'yellow', 'pink', 'blue'];
for (int i = 0; i < 10; i++) {
print(color.getElement(i));
}
}
extension EndlessElements<T> on List<T> {
T getElement(int index) {
return this[index >= this.length ? index % this.length : index];
}
}
【讨论】:
您可以使用while循环并通过使用余数来获取列表中的索引。
不确定您的用例是什么,但如果您在构建器或其他东西中调用它,您可以使用 index%4 来选择颜色。
List<Colour> color = ['Red', 'yellow', 'pink', 'blue'];
int count = 0;
while(count < 8){
print(color[count%4]);
count = count + 1;
}
【讨论】: