英文:
_TypeError (type 'int' is not a subtype of type 'double' in type cast)
问题
var randomValue = values[i];
在这一行中,我得到一个错误,类似于“_TypeError (type 'int' is not a subtype of type 'double' in type cast)”。
在initstate中调用了API,但显示了此错误。你能帮我找到错误并指出我的代码中有什么问题吗?
英文:
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 = [];
final List<double> values = List.castFrom(data['c']);
final List<int> timestamps = List.castFrom(data['t']);
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;
});
}
}
'''
var randomValue = values[i];
'''
In this line i am getting error like "_TypeError (type 'int' is not a subtype of type 'double' in type cast)"
In initstate api call is done but shows this error So can you help me to find error and what's wrong in my code
答案1
得分: 2
在Dart中,“cast”一词意味着将一个对象视为不同类型。它不会对该对象应用任何类型的转换。
你有:
final data = json.decode(response.body);
...
final List<double> values = List.castFrom(data['c']);
如果data
包含int
而不是double
,那么List<double>.castFrom
将无法帮助你,当你尝试访问int
元素时,会出现TypeError
。相反,你应该显式将元素转换为double
。例如:
final List<double> values = [for (var n in data['c'] ?? []) n.toDouble()];
或者:
final List<double> values = data['c']?.map((n) => n.toDouble()).toList();
英文:
In Dart, the term "cast" means treating an object as a different type. It does not apply any kind of transformation to that object.
You have:
final data = json.decode(response.body);
...
final List<double> values = List.castFrom(data['c']);
If data
contains int
s and not double
s, then List<double>.castFrom
will not help you, and you will end up with a TypeError
when you try to access an int
element. You instead should explicitly convert the elements to double
s. For example:
final List<double> values = [for (var n in data['c'] ?? []) n.toDouble()];
or:
final List<double> values = data['c']?.map((n) => n.toDouble()).toList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论