Ad

Text Widget In Flutter Shows Same Text For All Text Widgets In For Loop

- 1 answer

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.

Ad

Answer

I assume you end up with all having 25 as Text. The Text() have the same variable the whole time.

UPDATE:

The Text(_markersDistanceCount) you have is all pointing to the same variable, which in the end have the value of 25.

Try this instead:

for (var i = 0; i < 25; i++) {
  // Either
  final _distanceCount = _markersDistanceCount++;
  // Or rather
  final _distanceCount =  i + 1;

  markersDistance.add(
    Marker(
      point: LatLng(point.latitude, point.longitude),
      builder: (context) => CircleAvatar(
        radius: 50,
        backgroundColor: Colors.red,
        child: Text(_distanceCount.toString())
      ),
    ),
  );
}
Ad
source: stackoverflow.com
Ad