0

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)));

3 Answers 3

2

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])));
Sign up to request clarification or add additional context in comments.

5 Comments

On this way don't forget to add .toList() like List.generate(...).toList()
Huh? List.generate already generates a List, so .toList() wouldn't be necessary.
As I commented below, it's preferable for stringList to be declared as static const. In fact most IDEs will prompt you to do just that.
@RoslanAmir That's assuming that stringList is declared at class scope. static doesn't make sense if it's a top-level variable or a local variable.
@jamedlin, right. In that case it should be declared as final. I am suggesting this because this answer will be read in the future by others and should be using best practices.
2

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))];

Comments

1

I just found the solution, but two lines.

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

1 Comment

titles should be declared as static const not var.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.