这可能是一个基本问题,但我正试图从下面的JSON数据计算税。然而,每次我试图打印结果时,我都会得到这个消息。
未捕获错误:TypeError: Instance of 'JsLinkedHashMap<String,>': type 'JsLinkedHashMap<String,>'不是类型'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);
}
运行循环的原因是data
列表中可能有多个对象。
您的代码不正确。
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);
}