ken*_*wen 3 dart flutter google-cloud-firestore
weight是一个字段(Firestore中的数字),设置为100.
int weight = json['weight'];
double weight = json['weight'];
Run Code Online (Sandbox Code Playgroud)
int weight工作正常,100按预期返回,但double weight崩溃(Object.noSuchMethod异常)而不是返回100.0,这是我的预期.
但是,以下工作:
num weight = json['weight'];
num.toDouble();
Run Code Online (Sandbox Code Playgroud)
cre*_*not 18
100从Firestore 解析(实际上不支持"数字类型",但转换它)时,它将通过标准解析为int.
Dart不会自动"巧妙"地施放这些类型.事实上,你不能投int一个double,这是你面临的问题.如果可能,您的代码将正常工作.
相反,你可以自己解析它:
double weight = json['weight'].toDouble();
Run Code Online (Sandbox Code Playgroud)
还有什么用,将JSON解析为a num,然后将其分配给a double,将其转换num为double.
double weight = json['weight'] as num;
Run Code Online (Sandbox Code Playgroud)
这看起来有点奇怪,实际上Dart分析工具(例如内置在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"
Run Code Online (Sandbox Code Playgroud)
double b = 100 as num编译因为num是超阶级的double和飞镖投射超级亚类型,即使没有明确的强制转换.
一个显式转换将是follwing:
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
Run Code Online (Sandbox Code Playgroud)
你怎么了以下几点:
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
Run Code Online (Sandbox Code Playgroud)
您可以在一行中完成:
double weight = (json['weight'] as num).toDouble();
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以解析数据,如下所示:
这里的文档是一个Map<String,dynamic>
double opening = double.tryParse(document['opening'].toString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8899 次 |
| 最近记录: |