iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝
Using IIFEs in Dart: Assigning Values to Final Variables with If Statements
You can write it like this.
It uses fewer parentheses than JavaScript.
It is recommended to specify the type during variable declaration to reduce errors.
final num = 42;
final String message = () {
if (num == 42) {
return 'this is answer.';
} else {
return 'wrong.';
}
}();
This is also useful for encapsulating variable scope within an immediately invoked function.
final String message = () {
final greeting = 'hello, world';
}();
/// `greeting` cannot be referenced from here
Discussion