The problem is that I want to parse from this: {"cost": 0} to double. So what I have now:
Full code:
factory ShippingMethod.fromJson(Map<String, dynamic> json) {
dynamic cost = json['cost'];
print(cost.runtimeType); // printing runtime type and I get it twice!
return ShippingMethod(
code: json['code'],
title: json['title'],
description: json['description'],
cost: cost.toDouble(),
taxClassId: json['tax_class_id'],
);
}
And prints:
I/flutter ( 480): int // first it gives me int
I/flutter ( 480): String // second it gives me String
E/flutter ( 480): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'toDouble'.
E/flutter ( 480): Receiver: "0"
E/flutter ( 480): Tried calling: toDouble()
In addition, here is what I have from server:
...
"pickup": {
"code": "pickup.pickup",
"title": "Standard",
"description": "If the cost of the order ...",
"cost": 0,
"tax_class_id": 0,
"text": "0.00 TMT"
}
...
Dart made my day!.. Is it a bug or what?
double.parse(String)
json["cost"]
is returning an int value, so we should convert it to a string, then we can pass it to "double.parse(String)
".Solution Code:
double.parse(json["cost"].toString());