'Flutter: Illustrate List of Strings with a for-Loop doesn't work
I am really confused why does this only work without the braces around the for-Loop.
child: SingleChildScrollView(
child: Column(
children: [
for (int i = 1; i < lst.length; i++)
{
Container(
child: Card(
child: Text(lst[1]),
),
)
}
...
Solution 1:[1]
These are for
statements:
for (var i = 0; i < 10; i += 1)
print(i);
var someList = <int>[];
for (var i = 0; i < 10; i += 1) {
someList.add(i);
print(i);
}
Statements typically end with semicolons, and curly braces can group statements together. Statements do something.
You're not using a for
statement; you're using Dart's "collection-for
" syntax, which isn't actually a statement at all, nor does it contain any statements. It's an expression, and its body must also be an expression (or rather, an "element"). Expressions evaluate to a value that is consumed by other expressions (and usually ultimately to a statement).
Since collection-for
does not contain statements, braces are inappropriate (ditto for collection-if
), and the extraneous braces instead will be treated as creating a Set
literal.
I highly recommend reading the Making Dart a Better Language for UI article which describes the motivation and design of collection-for
and collection-if
.
Solution 2:[2]
That's just a matter of a syntax. Normal for loop in normal inline code works perfectly, but you use a special for operator in a dart collection. Same case with if statements.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Szymon Kowali?ski |