Flutter报错_TypeError:int无法转换为double类型的问题排查
问题定位与解决方案
错误根源
报错_TypeError (type 'int' is not a subtype of type 'double' in type cast)的核心原因是List.castFrom(data['c'])的使用方式错误。Finnhub API返回的c(收盘价)数组中可能同时包含整数和浮点数,而List.castFrom不会真正转换元素类型,仅做类型断言。当数组存在int类型值时,直接断言为List<double>会导致后续访问元素时触发类型不匹配。
修复代码
将列表元素逐个转换为目标类型,替代直接的类型断言:
Future<void> _fetchChartData() async { final response = await http.get(Uri.parse( 'https://finnhub.io/api/v1/stock/candle?symbol=${widget.symbol}&resolution=${widget.resolution}&from=${widget.fewDaysAgoTimestamp}&to=${widget.currentTimestamp}&token=$apiKey')); if (response.statusCode == 200) { final data = json.decode(response.body); final List<_ChartData> newChartData = []; // 安全转换收盘价为double类型 final List<double> values = (data['c'] as List) .map((e) => double.parse(e.toString())) .toList(); // 安全转换时间戳为int类型 final List<int> timestamps = (data['t'] as List) .map((e) => e as int) .toList(); for (int i = 0; i < values.length; i++) { final DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamps[i] * 1000); var randomValue = values[i]; newChartData.add( _ChartData(date, randomValue), ); if (i == 0) { _maxValue = _minValue = randomValue.toInt(); } else { _maxValue = max(_maxValue, randomValue.toInt()); _minValue = min(_minValue, randomValue.toInt()); } } setState(() { _chartData = newChartData; _isGoingUp = _chartData.first.y <= _chartData.last.y; }); } }
关键修改说明
- 替换
List.castFrom(data['c'])为map遍历转换:确保每个元素都被转为double,无论API返回的是整数还是浮点数。 - 时间戳列表也采用
map安全转换:避免潜在的类型异常,提升代码健壮性。
内容的提问来源于stack exchange,提问作者Not.Existt
相关产品推荐
相关产品推荐

