2

I have a list of Strings and an integer.

int number = 3;
var items = ['foo', 'hey','yo','bar', 'baz', 'qux'];

How can I split this list by the number(number of Lists to output).

Output :

List 1 = ['foo', 'hey']
List 2 = ['yo', 'bar']
List 3 = ['baz', 'qux']
user2827326
  • 61
  • 2
  • 8
  • see [chunked](https://pub.dev/documentation/more/latest/iterable/ChunkedExtension/chunked.html) method – pskink Feb 18 '21 at 05:24

2 Answers2

3
void main(List<String> args) {
  var n = 3;
  var items = ['foo', 'hey','yo','bar', 'baz', 'qux'];
  var m = (items.length / n).round();
  var lists = List.generate(n, (i) => items.sublist(m*i, (i+1)*m <= items.length ? (i+1)*m : null));

  print(lists);
}

Result:

[[foo, hey], [yo, bar], [baz, qux]]
2

Returns a new list containing the elements between start and end.

The new list is a List<E> containing the elements of this list at positions greater than or equal to start and less than end in the same order as they occur in this list.

var colors = ["red", "green", "blue", "orange", "pink"];
print(colors.sublist(1, 3)); // [green, blue]

If end is omitted, it defaults to the length of this list.

print(colors.sublist(1)); // [green, blue, orange, pink]

The start and end positions must satisfy the relations 0 ≤ start ≤ end ≤ this.length If end is equal to start, then the returned list is empty.

Implementation

List<E> sublist(int start, [int? end]);
Gourango Sutradhar
  • 1,461
  • 10
  • 16