Basics
Comments and Scope
A // comment is reader-only text that Dart skips at runtime. Each { ... } block introduces a new scope: a var declared inside disappears at the closing brace, while names from the enclosing scope stay visible.
Program
Play the program to enter an if block, build a label from inner state, then watch that inner name go out of scope.
comments_scope.dart
Replay: real traced execution (multi-file project)
void main() {
var label = 'outer';
// a reader-only comment; this does not run
if (label == 'outer') {
var detail = 'inner';
label = '$label/$detail';
}
print(label);
}
label ← outer
1void main() {2 var label = 'outer';3 // a reader-only comment; this does not runvalues this stepouterlabelcondition ← true
3// a reader-only comment; this does not run4if (label == 'outer') {5 var detail = 'inner';values this steptrueconditionouterlabeldetail ← inner
4if (label == 'outer') {5 var detail = 'inner';6 label = '$label/$detail';values this stepinnerdetaillabel ← outer/inner
5 var detail = 'inner';6 label = '$label/$detail';7}values this stepouter → outer/innerlabelinnerdetailprint(label);
7 }8 print(label);9}outputouter/innervalues this stepouter/innerlabel
Follow the Scope
labelstarts asouter.- The condition
label == 'outer'is true. - Inside the block,
detailisinner. labelbecomesouter/inner.- The program prints
outer/inner. | moment | visible value | | --- | --- | | start |label = outer| | condition | true | | inside block |detail = inner| | after update |label = outer/inner| | stdout |outer/inner|
// comment
Lines starting with `//` are for readers only; Dart skips them at runtime.
block scope
`var detail` declared inside the `{ ... }` block exists only there; the outer `label` stays visible.
after the brace
Past the closing `}` `detail` is gone, but `label` keeps its updated value.
Exercise: comments_scope.dart
Reproduce outer/inner, then identify which value exists only inside the block.