为什么我不能将数字转换为双精度数?
问题内容:
weight
是一个字段(Firestore中的 Number ),设置为100
。
int weight = json['weight'];
double weight = json['weight'];
int weight
工作正常,返回100
预期,但double weight
崩溃(Object.noSuchMethod
异常)而不是return 100.0
,这是我所期望的。
但是,以下工作原理:
num weight = json['weight'];
num.toDouble();
问题答案:
当分析100
从公司的FireStore(这实际上不支持“号码类型”,但将其转换),它将通过标准的被解析到一个 int
。
Dart 不会自动“智能”转换这些类型。实际上,您不能将int
转换为double
,这是您面临的问题。如果可能的话,您的代码就可以正常工作。
解析中
相反,您可以自己 解析 它:
double weight = json['weight'].toDouble();
铸件
什么也工作,是解析JSON的num
,然后将其分配给一个double
,这将投num
给double
。
double weight = json['weight'] as num;
乍一看似乎有些奇怪,实际上Dart
Analysis工具
(例如内置于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
是的超类,double
即使没有显式强制转换,Dart也会将超类型强制转换为子类型。
一个 显式的转换 将是以下:
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
说明
您发生了以下情况:
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