weight是一个字段(Firestore中的数字),设置为100.

int weight = json['weight'];
double weight = json['weight'];

int weight运行良好,按预期返回100,但double weight崩溃(Object.noSuchMethod异常),而不是我预期的返回100.0.

但是,以下功能可以正常工作:

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

推荐答案

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将转换为numdouble.

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

Dart相关问答推荐

为什么在穷举switch 表达式中需要显式向下转换?

基本数学函数的DART源代码

无法在 IOS 上使用 firebase 运行Flutter应用程序

在`lib`文件夹中使用`src`子文件夹有什么好处吗

Flutter-ExpansionTile 在点击时展开和折叠

如何处理 ListView 滚动方向

如何根据 Select 的选项卡更改样式?

如何删除ios上的overscroll?

使用brave浏览器调试flutter web app

表单的 TextFormField 中的多个光标(cursor)

如何解决Id does not exist错误?

Flutter类继承

Flutter:如何获取assets目录中所有图像的名称列表?

在 Dart 中实现观察者模式

Dart null 安全性不适用于类字段

dart和下划线

Dart vs Haxe - Current state, hype, usability, ...?

Dart 中不同的 Map 实现有什么区别?

有没有办法在 Dart 中通过引用传递原始参数?

Dart 字符串比较器