When parsing 100
from Firestore (which actually does not support a "number type", but converts it), it will by standard be parsed to an int
.
Dart does not automatically "smartly" cast those types. In fact, you cannot cast an int
to a double
, which is the problem you are facing. If it were possible, your code would just work fine.
解析
取而代之的是,您可以自己将其parse:
double weight = json['weight'].toDouble();
铸造
同样有效的方法是将JSON解析为num
,然后将其赋给double
,double
将转换为num
到double
.
double weight = json['weight'] as num;
乍一看这似乎有点奇怪,事实上,Dart Analysis tool(例如,内置于VS Code和IntelliJ的DART插件中)会将其标记为"unnecessary cast",但事实并非如此.
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
编译,因为double
中有num
is the super class个,即使没有显式强制转换,DART也会将超级类型强制转换为子类型.
下面是explicit cast:
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
Here is a nice read到"Types and casting in 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