I am building a simple stopwatch with State widget.
Initialize variables in State:
final laps = <int>[];
int milliseconds = 0;
milliseconds are updated in Timer every 0.1 seconds (after start button pressed):
setState((){
milliseconds = 100;
});
lap method updates list of laps (after lap button is pressed, when timer is running):
setState((){
laps.add(milliseconds);
});
And a method for displaying laps (running in build() on every setState):
for(int milliseconds in laps)
Text(_format(milliseconds))
The question is, if I forget to do type casting in for-in method, like this:
for(milliseconds in laps)
this wrecks the timer, and it just stops incrementing. It keeps running but milliseconds are just stuck at last value when lap was pressed. How so? I thought milliseconds is one variable, and laps list is another and it's values are yet another variables... This is confusing.
***DartPad with full code is https://dartpad.dev/?id=09114fd8f5332610042b1af85afdcae8 and without type casting (laps not working version). To get it work add int milliseconds at line 149. It takes a minute to run.
CodePudding user response:
when declaring a variable, you must either use Type variableName = value;
or var variableName = value
(you can also use final variableName = value;
or var variableName;
and I'm sure some others, but that's not the point).
when you do for (milliseconds in laps)
you neither put the type nor add var
or final
keyword. This would give you an error if you had not declared the milliseconds
variable before, because you have, it just assigns the value of each iteration to said variable, effectively breaking your code.
It's akin to this example
int i=183;
for (i=0; i<3; i ) {
print(i);
}
print(i);
If i run this code I get the following output:
0
1
2
2
If I add var, I get the following output:
0
1
2
183
So basically if you add var
or int
to the loop, you are redefining the variable inside the for-loop scope, if you don't you assign directly to the already existing variable, which in turn breaks the app.