是否有用于将平面列表转换为嵌套列表的 Dart 实用程序?



这是这里的常见问题,但我找不到任何简化的 Dart 方法 - 如何转换这样的列表

[1, 2, 3, 4, 5, 6]

进入这样的列表

[[1, 2], [3,4], [5,6]]

假设在此之后没有额外的元素?

Dart Quiver 包是一组用于 Dart 的实用程序库,它使使用许多 Dart 库更容易、更方便或添加额外的功能 (https://github.com/google/quiver-dart(。

您可以使用quiver迭代对象库中的分区函数,如下所示。

import 'package:quiver/iterables.dart';
main() {
var list = [1, 2, 3, 4, 5, 6];
# Use partition function to segment lists into chunks of size 2
var newList = partition<int>(list, 2);
print (newList);
}

结果

[[1, 2], [3,4], [5,6]]
var list = [1, 2, 3, 4];
List<int> temp = [];
List<List<int>> newList = list.fold<List<List<int>>>([], (newList, i) {
if (temp.length < 2) {
temp.add(i);
} 
if (temp.length >= 2) {
List<int> newValue = new List<int>.from(temp);
newList.add(newValue);
temp.clear();
}
return newList;
});
print(newList);

最新更新