Home > Blockchain >  Iterating through JSON map in Dart
Iterating through JSON map in Dart

Time:05-16

This may be a fundamental question but I'm trying to calculate tax from the JSON data below. However, I get this message every time I try to print the result.

Uncaught Error: TypeError: Instance of 'JsLinkedHashMap<String, Object>': type 'JsLinkedHashMap<String, Object>' is not a subtype of type 'int'

void main() {
  double tax = 0.0;
  int index = 0;
  Map<String, dynamic> test = {
    "data": {
        "cartItem": [
            {
                "id": 30,
                "productName": "Mango",
                "price": 100.0,
                "tax": 10.0,
                "quantity": 7,
                "mainImage": "http://3.109.206.91:8000/static/product_module/product/png-clipart-slice-of-mango-mango-tea-fruit-mango-game-food_HSPnZGK.png",
                "totalPrice": 700.0
            }
        ],
        "grandTotal": 700.0
    }
};
  
  for(index in test['data']['cartItem']) {
    tax  = (test['data']['cartItem'][index]['tax'] / 100.0);
  }
  print(tax);
}

The reason behind running a loop is that there may be more than one object inside the data list.

CodePudding user response:

Your code is incorrect.

void main() {
  double tax = 0.0;
  int index = 0;
  Map<String, dynamic> test = {
    "data": {
      "cartItem": [
        {
          "id": 30,
          "productName": "Mango",
          "price": 10.0,
          "tax": 10.0,
          "quantity": 7,
          "mainImage":
              "http://3.109.206.91:8000/static/product_module/product/png-clipart-slice-of-mango-mango-tea-fruit-mango-game-food_HSPnZGK.png",
          "totalPrice": 700.0
        }
      ],
      "grandTotal": 700.0
    }
  };

  for (final cartItem in test['data']['cartItem']) {
    tax  = (cartItem['tax'] as num) / 100.0;
  }
  print(tax);
}

  •  Tags:  
  • dart
  • Related