Search code examples
flutterdart

Json int to double parsing Flutter


The problem is that I want to parse from this: {"cost": 0} to double. So what I have now:

  1. json['cost'].toDouble(), error: Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'toDouble'.
  2. int.parse(json['cost']).toDouble(), error: Unhandled Exception: type 'int' is not a subtype of type 'String'
  3. json['cost'], error: Unhandled Exception: type 'int' is not a subtype of type 'double'

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?


Solution

    1. to convert a string to double we have a function: double.parse(String)
    2. 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());