gpt4 book ai didi

flutter - Json int双重解析Flutter

转载 作者:行者123 更新时间:2023-12-03 04:34:00 40 4
gpt4 key购买 nike

问题是我想从此解析:{“cost”:0}翻倍。所以我现在有:

  • json ['cost']。toDouble(),错误:未处理的异常:NoSuchMethodError:类'String'没有实例方法'toDouble'。
  • int.parse(json ['cost'])。toDouble(),错误:未处理的异常:类型'int'不是类型'String'的子类型
  • json ['cost'],错误:未处理的异常:类型'int'不是类型'double'的子类型

  • 完整代码:
    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'],
    );
    }
    并打印:
    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()
    另外,这是我从服务器获得的内容:
    ...
    "pickup": {
    "code": "pickup.pickup",
    "title": "Standard",
    "description": "If the cost of the order ...",
    "cost": 0,
    "tax_class_id": 0,
    "text": "0.00 TMT"
    }
    ...
    Dart让我开心!..是bug还是什么?

    最佳答案

  • 将字符串转换为 double ,我们有一个函数:double.parse(String)
  • json["cost"]返回一个int值,因此我们应该将其转换为字符串,然后将其传递给“double.parse(String)”。

  • 解决方案代码:
    double.parse(json["cost"].toString());

    关于flutter - Json int双重解析Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64426910/

    40 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com