Since not everything from dart is an expression (Like Kotlin) I wonder how it is possible that the next code runs:
I do a for loop that returns somehow each array item, it's like a deconstruction but with another syntax.
void main() {
final numbers = [1, 2, 3];
final computedNumbers = [for(final n in numbers) n];
print(computedNumbers);
}
It prints: [1, 2, 3]
In Flutter you could build an array if ifs like:
[
Text("My Text"),
// Compiles fine
if (myExpressionIsTrue) Text("Optional Text")
]
And at the end it creates a "deconstructed" array without the element if myExpressionIsTrue
is true. One thing that confuses me is that if I put the if with {}
it does not compile, like this:
[
Text("My Text"),
if (myExpressionIsTrue) { // This fails at compile time
Text("Optional Text")
}
]
The question is how it is possible that it works since if
or for
are not expressions, and what is the name of the language feature that allows this?
The name of that feature is collection for and collection if. See the Lists section of the Dart Language Tour.
I also highly recommend reading the article Making Dart a Better Language for UI, which discusses a lot of the considerations that went into the design of the feature.