Flutter Dart数组固定长度分割
2019-10-13 本文已影响0人
readonly__
将dart数组按照指定的长度分割,返回一个二维数组,实现list的split功能.
```
eg:
源数组:a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
splitList(a, 6):[[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19]]
```
代码如下:
```dart
static List<List<T>> splitList<T>(List<T> list, int len) {
if (len <= 1) {
return [list];
}
List<List<T>> result = List();
int index = 1;
while (true) {
if (index * len < list.length) {
List<T> temp = list.skip((index - 1) * len).take(len).toList();
result.add(temp);
index++;
continue;
}
List<T> temp = list.skip((index - 1) * len).toList();
result.add(temp);
break;
}
return result;
}
```