一尘不染

为什么我不能将数字转换为双精度数?

flutter

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

阅读 316

收藏
2020-08-13

共1个答案

一尘不染

当分析100从公司的FireStore(这实际上不支持“号码类型”,但将其转换),它将通过标准的被解析到一个 int
Dart 不会自动“智能”转换这些类型。实际上,您不能将int转换为double,这是您面临的问题。如果可能的话,您的代码就可以正常工作。

解析中

相反,您可以自己 解析 它:

double weight = json['weight'].toDouble();

铸件

什么也工作,是解析JSON的num,然后将其分配给一个double,这将投numdouble

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

这是有关
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
2020-08-13