Dart或Flutter中解决异常-type ‘int‘ is not a subtype of type ‘double‘

出现场景

服务端返回的金额数据可能是整数,也可能是小数。

无论我们按int或double来解析,都可能出错。

如果我们定义的类型是int,返回的是double就会报以下异常。

int money = data["money"];
type 'int' is not a subtype of type 'double'

如果我们定义的类型是double,返回的是int就会报以下异常。

double money = data["money"];
type 'double' is not a subtype of type 'int'

解决方案

Dart不像JavaScript一样能自动转换,需要我们按具体类型处理。

声明num(推荐)

使用num类型来接收服务端返回的值。

/// 会自动转换成对应的类型
num money = data["money"];

num源码

part of dart.core;

/// An integer or floating-point number.
///
/// It is a compile-time error for any type other than [int] or [double]
/// to attempt to extend or implement `num`.
///
/// **See also:**
/// * [int]: An integer number.
/// * [double]: A double-precision floating point number.
/// * [Numbers](https://dart.dev/guides/language/numbers) in
/// [A tour of the Dart language](https://dart.dev/guides/language/language-tour).

abstract class num implements Comparable<num> {
	...
}

查看num源码得知,num是一个int整形或者double浮点型,会自动根据右边赋值的类型决定自身的类型。

判断类型

这种方式稍微麻烦一点,根据返回的不同类型做不同的处理。

声明类型为double的方式

double money = 0.0;
var result = data["money"];
if(result is int){
	money = result.toDouble();
} else{
	money = result;
}

声明类型为int的处理方式

int money = 0;
var result = data["money"];
if(result is int){
	money = result;
} else{
	money = result.toInt();
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值