类型错误(类型’int’不是类型’double’中类型转换的子类型)

huangapple go评论93阅读模式
英文:

_TypeError (type 'int' is not a subtype of type 'double' in type cast)

问题

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;
      });
    }
  }

在这行代码中,我遇到了一个错误:"TypeError (type 'int' is not a subtype of type 'double' in type cast)"。

在initstate中,API调用已经完成,但是显示了这个错误。所以你能帮我找到错误,并告诉我代码中的问题在哪里吗?

英文:
Future&lt;void&gt; _fetchChartData() async {
    final response = await http.get(Uri.parse(
        &#39;https://finnhub.io/api/v1/stock/candle?symbol=${widget.symbol}&amp;resolution=${widget.resolution}&amp;from=${widget.fewDaysAgoTimestamp}&amp;to=${widget.currentTimestamp}&amp;token=$apiKey&#39;));

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      final List&lt;_ChartData&gt; newChartData = [];

      final List&lt;double&gt; values = List.castFrom(data[&#39;c&#39;]);
      final List&lt;int&gt; timestamps = List.castFrom(data[&#39;t&#39;]);

      for (int i = 0; i &lt; 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 &lt;= _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&lt;double&gt; values = List.castFrom(data[&#39;c&#39;]);

If data contains ints and not doubles, then List&lt;double&gt;.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 doubles. For example:

final List&lt;double&gt; values = [for (var n in data[&#39;c&#39;] ?? []) n.toDouble()];

or:

final List&lt;double&gt; values = data[&#39;c&#39;]?.map((n) =&gt; n.toDouble()).toList();

huangapple
  • 本文由 发表于 2023年8月9日 12:03:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定