Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 在数组长度中保留int值_Flutter_Dart - Fatal编程技术网

Flutter 在数组长度中保留int值

Flutter 在数组长度中保留int值,flutter,dart,Flutter,Dart,我有一个列表视图和颜色列表。我想使用列表中的颜色更改每个列表项的背景。为了做到这一点,我创建了一个简单的递归函数,帮助我给出索引编号,以避免索引外错误 例如:我的列表中有5种颜色,如果我尝试访问超过第4种颜色的索引,则会显示“超出数组”错误。我的函数就是这么做的 我的递归函数: getColorIndex(int index) { return index <= 4 ? index : getColorIndex(index - 5); } getColorIndex(int-i

我有一个列表视图和颜色列表。我想使用列表中的颜色更改每个列表项的背景。为了做到这一点,我创建了一个简单的递归函数,帮助我给出索引编号,以避免索引外错误

例如:我的列表中有5种颜色,如果我尝试访问超过第4种颜色的索引,则会显示“超出数组”错误。我的函数就是这么做的

我的递归函数:

getColorIndex(int index) {
    return index <= 4 ? index : getColorIndex(index - 5);
}
getColorIndex(int-index){

返回指数您应该阅读关于模(%)的内容,这是计算机科学和普通数学中非常常见的概念:

因此,您的方法可以重写为:

void main() {
  for (var i = 0; i < 10; i++) {
    print('index = $i | Color Index: ${getColorIndex(i)}');
  }
}

int getColorIndex(int index) => index % 5;

但是您通常应该做的是:
myList[index%myList.length]
这是推荐的方法,因为它是最清晰的方法。

谢谢你的方法比我的好,但我正在寻找一些核心dart函数或列表类的方法。我没有写这篇文章,所以这是我的错。通常,你甚至不会为此声明方法,只需声明:
myList[index%myList.length]
。如果这对你来说太难看了,你也可以在
列表中添加一个扩展方法来处理它。现在已经很晚了,我想我的大脑不工作了。就是这么简单。谢谢你的帮助。这就是我要找的。简单明了。我不知道这个“扩展方法”的东西和T关键字,但我现在已经学会了。你已经知道了我比我的老师更喜欢:)谢谢你,先生。就我个人而言,我发现刚开始使用模更干净、更具描述性,为这样一个简单的操作(甚至是扩展方法)创建函数是一个丑陋的选择。我想,对每个人来说,都是这样。