skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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(),
                    );
                  });
                })(),
            ],
          ),
        ),
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search