类型'int'不是类型'double'的子类型-飞镖/颤振错误

时间:2020-04-23 22:45:55

标签: json flutter dart

所以我有一个API设置,当调用该API时,它将在特定端点上返回以下输出:

{
    "total_user_currency": 0.1652169792,
    "total_sats": 2184,
    "total_btc": 0.00002184,
    "outputArray": [
        {
            "txid": "642fd534cb3a670a31f4d59e70452b133b0b461d871db44fcc91d32bb6b6f0cc",
            "vout": 2,
            "status": {
                "confirmed": true,
                "block_height": 625673,
                "block_hash": "0000000000000000000310649c075b9e2fed9b10df2b9f0831efc4291abcb7fb",
                "block_time": 1586732907
            },
            "value": 546
        },

    ]
}

我正在使用以下dart类将JSON解码为可以与之交互的对象:

class UtxoData {
  final dynamic totalUserCurrency;
  final int satoshiBalance;
  final dynamic bitcoinBalance;
  List<UtxoObject> unspentOutputArray;

  UtxoData({this.totalUserCurrency, this.satoshiBalance, this.bitcoinBalance, this.unspentOutputArray});

  factory UtxoData.fromJson(Map<String, dynamic> json) {
    var outputList = json['outputArray'] as List;
    List<UtxoObject> utxoList = outputList.map((output) => UtxoObject.fromJson(output)).toList(); 

    return UtxoData(
      totalUserCurrency: json['total_user_currency'],
      satoshiBalance: json['total_sats'],
      bitcoinBalance: json['total_btc'],
      unspentOutputArray: utxoList
    );
  }
}

class UtxoObject {
  final String txid;
  final int vout;
  final Status status;
  final int value;

  UtxoObject({this.txid, this.vout, this.status, this.value});

  factory UtxoObject.fromJson(Map<String, dynamic> json) {
    return UtxoObject(
      txid: json['txid'],
      vout: json['vout'],
      status: Status.fromJson(json['status']),
      value: json['value']
    );
  }
}

class Status {
  final bool confirmed;
  final String blockHash;
  final int blockHeight;
  final int blockTime;

  Status({this.confirmed, this.blockHash, this.blockHeight, this.blockTime});

  factory Status.fromJson(Map<String, dynamic> json) {
    return Status(
      confirmed: json['confirmed'],
      blockHash: json['block_hash'],
      blockHeight: json['block_height'],
      blockTime: json['block_time']
    );
  }

}

这是在代码中实际调用API的函数:

Future<UtxoData> fetchUtxoData() async {
    final requestBody = {
      "currency": "USD",
      "receivingAddresses": ["bc1q5jf6r77vhdd4t54xmzgls823g80pz9d9k73d2r"],
      "internalAndChangeAddressArray": ["bc1q5jf6r77vhdd4t54xmzgls823g80pz9d9k73d2r"]
    };

    final response = await http.post('https://thisisanexmapleapiurl.com', body: jsonEncode(requestBody), headers: {'Content-Type': 'application/json'} );

    if (response.statusCode == 200 || response.statusCode == 201) {
      notifyListeners();
      print(response.body);
      return UtxoData.fromJson(json.decode(response.body));
    } else {
      throw Exception('Something happened: ' + response.statusCode.toString() + response.body );
    }
  }

但是,当我运行该函数时,在编辑器中出现以下错误:

Exception has occurred.
_TypeError (type 'int' is not a subtype of type 'double')

我在UtxoData类的工厂方法内的return UtxoData语句中得到它,如下所示:

return UtxoData(
      totalUserCurrency: json['total_user_currency'],
      satoshiBalance: json['total_sats'],                    <<<<============= The exception pops up right there for some reason
      bitcoinBalance: json['total_btc'],
      unspentOutputArray: utxoList
    );

这很奇怪,因为我知道API在那里返回一个int。 totalUserCurrency和bitcoinBalance必须是动态的,因为它们可以是0(整数)或任意数字,例如12942.3232(双精度)。

为什么会出现此错误,我该如何纠正?非常感谢

2 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,我从API获得的金额介于0到几千之间(包括小数)。我尝试了以下方法:

this.balanceAmount = double.parse(json['total_balance']??'0.0'.toString());

这不适用于我的数据集。因此,我将其增强为以下情况,适用于我的数据集的所有情况。您可能需要一些改进。

double parseAmount(dynamic dAmount){

    double returnAmount = 0.00;
    String strAmount;

    try {

      if (dAmount == null || dAmount == 0) return 0.0;

      strAmount = dAmount.toString();

      if (strAmount.contains('.')) {
        returnAmount = double.parse(strAmount);
      }  // Didn't need else since the input was either 0, an integer or a double
    } catch (e) {
      return 0.000;
    }

    return returnAmount;
  }

答案 1 :(得分:1)

如果您正在解析数据,并且不确定是Int还是double,那么有多种解决方案。

如果您需要Int,请使用parsedData.truncate(),这对Intdouble都适用,并且可以通过舍弃小数来解析为Int。同样,如果希望小数点对结果有影响,也可以使用cail()floor()

因此,就您而言,您只需要这样做:

satoshiBalance: json['total_sats'].truncate(),

我希望这会有所帮助!