flutterdart

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?

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