Home > Net >  Array generate in one single line
Array generate in one single line

Time:04-26

How can I generate an array of DataColumn in one single line?

<DataColumn>[
  DataColumn(label: Text('A')),
  DataColumn(label: Text('B')),
  DataColumn(label: Text('C')),
  DataColumn(label: Text('D')),
]

Such as:

list<DataColumn>.gen(['A','B','C','D'], (string) => DataColumn(label: Text(string)));

CodePudding user response:

You can use List.generate() like is:

List<String> stringList = ['ACTIVE', 'MODE', 'SEMI', 'AUTO'];

Colum(children: List.generate(stringList.length, (int index) => DataColumn(label: Text(stringList[index])));

CodePudding user response:

I just found the solution, but two lines.

var titles = ['A', 'B', 'C', 'D'];
List.generate(titles.length,(index) => DataColumn(label: Text(titles[index])));

CodePudding user response:

You can use Iterable.map:

var columns = ['A', 'B','C', 'D'].map((s) => DataColumn(label: Text(s))).toList();

or collection-for, which is slightly shorter:

var columns = [for (var s in ['A', 'B', 'C', 'D']) DataColumn(label: Text(s))];
  • Related