Skip to content

prefer_for_loop_in_children

v0.4.0 Warning Fix Code Organization

Flags functional list-building patterns like .map().toList(), List.generate(), .fold(), and spread with .map() that can be replaced with Dart’s collection-for syntax. Collection-for is more idiomatic, avoids intermediate allocations, and reads more naturally in widget trees.

Collection-for syntax ([for (final item in items) Widget(item)]) is the idiomatic Dart way to build lists inline. It avoids creating intermediate iterables, integrates naturally with collection-if for conditional elements, and is easier to read in deeply nested widget trees than chained method calls.

See also: Flutter - Column children | Flutter - Row children

// .map().toList()
Column(
children: items.map((item) => Text(item)).toList(),
);
// spread with .map()
Column(
children: [
const Text('Header'),
...items.map((item) => Text(item)),
],
);
// List.generate()
Column(
children: List.generate(5, (index) => Text('Item $index')),
);
// .fold() to accumulate widgets
final widgets = items.fold<List<Widget>>([], (list, item) {
list.add(Text(item));
return list;
});
// collection-for syntax
Column(
children: [for (final item in items) Text(item)],
);
// collection-for with index
Column(
children: [for (var i = 0; i < 5; i++) Text('Item $i')],
);
// mixed with other children
Column(
children: [
const Text('Header'),
for (final item in items) Text(item),
const Text('Footer'),
],
);

To disable this rule:

plugins:
many_lints:
diagnostics:
prefer_for_loop_in_children: false