Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is indexOf returning zero if used with json.decode

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
               ),
      ),
   );
}

>Solution :

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:

Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      child: Column(
        children: [
          for (var item in values)
            Text(
              (values.indexOf(item) + 1).toString(),
            ),
          for (var item in values)
            ...(() {
              // Decode once and reuse the result
              final decodedResult = json.decode(item.details?["result"]) as List;
              return decodedResult.map((item2) {
                return Text(
                  (decodedResult.indexOf(item2) + 1).toString(),
                );
              });
            })(),
        ],
      ),
    ),
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading