In flutter, I have this code that returns zero for all item2
:
for (var item2 in json.decode(item.details?["result"]))
Text(
((json.decode(item.details?["result"])).indexOf(item2) + 1).toString()
),
My question is why does the above code output 0
, while the below code shows the correct index:
for (var item in values)
Text(
(values.indexOf(item) + 1).toString()
),
UPDATE: My actual code is below, so I cannot really declare a new variable inside the for loop…or can I?
Widget build(BuildContext context) {
return Scaffold(
body: Container(
...
for (var item in values)
Text(
(values.indexOf(item) + 1).toString()
),
for (var item2 in json.decode(item.details?["result"]))
Text(
((json.decode(item.details?["result"])).indexOf(item2) + 1).toString()
),
),
);
}
2
Answers
The issue arises because json.decode generates new objects each time it’s called, and indexOf in Dart compares objects by reference for complex types like lists, maps, or other objects
You can declare a new variable to hold the decoded result outside the loop. This avoids repeatedly decoding the same JSON string and ensures consistent behavior. Here’s how: