解析时100
来自Firestore(实际上不支持“数字类型”,但是转换它 https://firebase.google.com/docs/firestore/manage-data/data-types),按照标准,它将被解析为int
.
Dart不会自动“智能”地转换这些类型。事实上,你不能施放int
to a double
,这就是您面临的问题。如果可能的话,您的代码就会正常工作。
Parsing
相反,您可以parse自己做:
double weight = json['weight'].toDouble();
Casting
同样有效的是将 JSON 解析为num
然后将其分配给double
,这将投射num
to double
.
double weight = json['weight'] as num;
乍一看这似乎有点奇怪,但事实上飞镖分析工具 https://pub.dartlang.org/packages/analyzer(例如,内置于 VS Code 和 IntelliJ 的 Dart 插件中)将其标记为“不必要的演员”,但事实并非如此。
double a = 100; // this will not compile
double b = 100 as num; // this will compile, but is still marked as an "unnecessary cast"
double b = 100 as num
编译是因为num是超级类 https://api.dartlang.org/stable/1.24.3/dart-core/num-class.html of double https://api.dartlang.org/stable/1.24.3/dart-core/double-class.html即使没有显式强制转换,Dart 也会将超级类型强制转换为子类型。
An 显式转换将是以下内容:
double a = 100 as double; // does not compile because int is not the super class of double
double b = (100 as num) as double; // compiles, you can also omit the double cast
这是一篇很好的读物 https://news.dartlang.org/2012/05/types-and-casting-in-dart.html about “Dart 中的类型和铸造”.
解释
您遇到的情况如下:
double weight;
weight = 100; // cannot compile because 100 is considered an int
// is the same as
weight = 100 as double; // which cannot work as I explained above
// Dart adds those casts automatically