You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Bitcoin Ticker项目类型转换错误求助:类型不兼容

解决Bitcoin Ticker项目中的类型不兼容错误

错误1:type 'int' is not a subtype of type 'double'

问题根源:CoinGecko API返回的行情数值不一定都是double类型,部分场景下会返回int(比如用JPY计价时),直接赋值给double变量会触发类型转换失败。

修复方案:
修改coin_data.dart中提取价格的代码,把原始数值强制转为double类型:

// 替换原来的double currencyValue = ... 这一行
dynamic rawPrice = decodedData[crypto][selectedCurrency];
double currencyValue = rawPrice is int ? rawPrice.toDouble() : rawPrice;

错误2:type '_Map<String, String>' is not a subtype of type 'double'

问题根源:getCoinData()方法返回的是包含所有加密货币价格的Map<String, String>,但price_screen.dart的getData方法错误地将其当作double类型接收,类型完全不匹配。

修复方案:

  1. 修正getData方法的变量接收类型,并直接更新状态中的coinValues:
void getData(String selectedCurrency) async {
  isWaiting = true;
  try {
    // 把double改为Map<String, String>
    Map<String, String> data = await CoinData().getCoinData(selectedCurrency);
    isWaiting = false;
    setState(() {
      // 直接将返回的完整Map赋值给coinValues
      coinValues = data;
    });
  } catch (e) {
    print(e);
  }
}
  1. 给getCoinData方法显式声明返回类型,避免隐式类型问题(可选但推荐):
// 修改coin_data.dart中的方法签名
Future<Map<String, String>> getCoinData(String selectedCurrency) async {

额外优化建议

  • 注意cryptoList中的lightcoin是拼写错误,正确的应该是litecoin,否则API会返回错误数据。
  • 可以给decodedData的访问添加空值判断,避免空指针异常,比如:
if (decodedData.containsKey(crypto) && decodedData[crypto]!.containsKey(selectedCurrency)) {
  // 提取价格的逻辑
} else {
  throw 'API返回数据格式异常';
}

内容的提问来源于stack exchange,提问作者Shridhar Ashok Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:44:51