[Solved] how to make List<List> using List?

Question

Asked by jichang b on January 03, 2022 (source).

I have to make List<List> using List

  List<String> list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' , '11', '12', '13', '14', '15', '16', '17', '18' , '19', '20', '21', '22', '23', '24', '25'];

list.length will be no more than 25.

have to divide by 5 like

  int divide;
  
  divide = word.length ~/ 5;

and have to make List<List>

I don't know how to do it.

have to be

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20],[21, 22, 23, 24, 25]]

if list.length is 23 have to be

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20],[21, 22, 23]]

Answer

Question answered by Sam C (source).

You can try this one

List dataList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' , '11', '12', '13', '14', '15', '16', '17', '18' , '19', '20', '21', '22'];
List chunkList = [];
int chunkSize = 5;
for (var i = 0; i < dataList.length; i += chunkSize) {
    chunkList.add(dataList.sublist(i, i+chunkSize > dataList.length ? dataList.length : i + chunkSize)); 
  }
print(chunkList);
FLUTTER
SHARE: