'Text widget in Flutter shows same text for all Text widgets in for loop
In Flutter, I am using a Text widget in a for loop. The console shows a nice increasing list of numbers. However all 25 Text widgets show 25.
It looks like the Text widget does make a reference to _markersDistanceCount instead of using their value.
I've also tried to jsonEncode and jsonDecode the values, but still they are all 25. Does anyone know what I am doing wrong?
var _markersDistanceCount = 0;
for (var i = 0; i < 25; i++) {
_markersDistanceCount++;
print(_markersDistanceCount);
markersDistance.add(
Marker(
point: LatLng(point.latitude, point.longitude),
builder: (context) => CircleAvatar(
radius: 50,
backgroundColor: Colors.red,
child: Text(_markersDistanceCount.toString())
),
),
);
}
When I change Text(_markersDistanceCount.toString()) to Text(i.toString()) there is no issue and Text widgets are containing the correct i value.
Solution 1:[1]
The value of _markersDistanceCount becomes 25 before reaching the Marker's builder method. To explore it I've debugged the code, here I am using an inline method to show the situation. I am not aware of this type of behavior, just exploring the issue.
@override
void initState() {
super.initState();
int _markersDistanceCount = 0;
for (int i = 0; i < 25; i++) {
_markersDistanceCount++;
markersDistance.add(
() {
debugPrint("OnTop=> i: $i mkNUm: ${_markersDistanceCount.toInt()}");
return Marker(
key: ValueKey("tm $_markersDistanceCount"),
point: () {
debugPrint(
"On point=> i: $i mkNUm: ${_markersDistanceCount.toInt()}");
return LatLng(51.5 + (i * .01), -0.09);
}(),
builder: (context) {
///this gets call after while `_markersDistanceCount:25` completing the loop
debugPrint(
"insideBuild=> i: $i mkNUm: ${_markersDistanceCount.toInt()}");
return CircleAvatar(
radius: 50,
backgroundColor: Colors.red,
child: Text(
_markersDistanceCount.toDouble().toString(),
),
);
});
}(),
);
}
}
This will print
OnTop=> i: 0 mkNUm: 1
On point=> i: 0 mkNUm: 1
OnTop=> i: 1 mkNUm: 2
On point=> i: 1 mkNUm: 2
OnTop=> i: 2 mkNUm: 3
.....
OnTop=> i: 24 mkNUm: 25
On point=> i: 24 mkNUm: 25
insideBuild=> i: 0 mkNUm: 25
insideBuild=> i: 1 mkNUm: 25
As for the solution, you can use i while both share the same responsibility.
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 | Yeasin Sheikh |
