“int”类型不是“double”类型的子类型

Mah*_*ika 15 android dart flutter

我的颤振应用程序有这个问题。似乎无法加载 API 请求,但是当我在浏览器上尝试时,它返回正常“ http://vplay.id/api/series/popular ”。

调试

exception = {_Exception} Exception: Failed to load
message = "Failed to load"
this = {SeriesProvider} 
 _url = "http://vplay.id/api/"
 _loading = false
 _currentPage = 1
 _pages = 1
 _series = {_GrowableList} size = 0
 _seriesStream = {_AsyncStreamController} 
endpoint = "series/popular"
e = {_TypeError} type 'int' is not a subtype of type 'double'
 _stackTrace = {_StackTrace} 
 _failedAssertion = "is assignable"
 _url = "package:streamapp/src//helpers/parse.dart"
 _line = 31
 _column = 7
 message = "type 'int' is not a subtype of type 'double'"
Run Code Online (Sandbox Code Playgroud)

系列_provider.dart

import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;
import '../helpers/api.dart';
import '../models/serie_model.dart';
export '../models/serie_model.dart';

class SeriesProvider {
  String _url = Api.url;
  bool _loading = false;
  int _currentPage = 1;
  int _pages = 1;
  List<Serie> _series = List();
  final _seriesStream = StreamController<List<Serie>>();

  Function(List<Serie>) get seriesSink => _seriesStream.sink.add;
  Stream<List<Serie>> get seriesStream => _seriesStream.stream;

  void dispose() {
    _seriesStream?.close();
  }

  Future<List<Serie>> _process(String endpoint) async {
    try {
      final resp = await http.get(_url + endpoint);

      if (resp.statusCode != 200) {
        throw Exception('Failed to load');
      }

      final data = json.decode(resp.body);

      final series = Series.fromJsonList(data);

      return series.items;
    } catch (e) {
      throw Exception('Failed to load');
    }
  }
Run Code Online (Sandbox Code Playgroud)

助手/parse.dart

static double checkDouble(dynamic value) {
    if (value is String) {
      return double.parse(value);
    } else {
      return value;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我第一次使用 flutter,这很有趣,因为只有我在全新安装时才会遇到这个问题(这是我从 codecanyon 市场获得的应用程序)。

Dep*_*ver 26

一个想法是使用num代替intdouble在这种情况下。

  • @Kiax int 和 double 都继承自 num (2认同)
  • 这是一个很好的解决方案!谢谢 (2认同)

小智 9

您只需要将 .toDouble() 函数添加到最后返回的值。

static double checkDouble(dynamic value) {
    if (value is String) {
      return double.parse(value);
    } else {
      return value.toDouble;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Sze*_*obe 9

正如下面提到的 Gustavo Rodrigues,不要将其用作标准解决方案,这只是一种解决方法。

我在获取天气数据时遇到了类似的问题。

我通过将变量声明为dynamic而不是int类型来解决。

  • 请永远不要使用此解决方案。动态将你的类型安全抛到了九霄云外。保罗·康德的回答(/sf/answers/4404912431/)是正确的。如果您正在使用需要编组为双倍的 JSON,只需在末尾添加 .toDouble 即可。 (11认同)

小智 8

static double checkDouble(dynamic value) {
    if (value is String) {
      return double.parse(value);
    } else {
      return value;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

问题似乎从上次开始return value。您可能需要return value+.0.