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

简介: 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();
}
相关文章
|
2月前
Flutter-解决Try catch出现异常:type ‘_TypeError‘ is not a subtype of type ‘Exception‘ in type cast
Flutter-解决Try catch出现异常:type ‘_TypeError‘ is not a subtype of type ‘Exception‘ in type cast
56 1
|
8天前
|
Dart
如何在 Flutter 项目中使用 Dart 语言?
如何在 Flutter 项目中使用 Dart 语言?
108 58
|
2月前
|
Dart 前端开发 JavaScript
Flutter&Dart-异步编程Future、Stream极速入门
Flutter&Dart-异步编程Future、Stream极速入门
59 4
Flutter&Dart-异步编程Future、Stream极速入门
|
2月前
|
Dart
Flutter笔记:手动配置VSCode中Dart代码自动格式化
Flutter笔记:手动配置VSCode中Dart代码自动格式化
174 5
|
2月前
Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘MaterialColor‘
Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘MaterialColor‘
32 4
|
2月前
|
Dart 开发工具 Android开发
Android Studio导入Flutter项目提示Dart SDK is not configured
Android Studio导入Flutter项目提示Dart SDK is not configured
93 4
|
2月前
|
Dart 开发工具
解决升级Flutter3.0后出现警告Operand of null-aware operation ‘!‘ has type ‘WidgetsBinding‘ which excludes null
解决升级Flutter3.0后出现警告Operand of null-aware operation ‘!‘ has type ‘WidgetsBinding‘ which excludes null
27 1
|
3月前
|
JSON Dart 安全
Flutter Dart Macro 宏简化 JSON 序列化
今天我们将会体验 dart 语言新特性 macro 宏,来实现对 json 的序列化,用到的包是官方实验室写的 json 包。 本文将会一步步的带你实现这个功能,那我们开始吧。
Flutter Dart Macro 宏简化 JSON 序列化
|
2月前
|
Dart 安全 API
Android跨平台开发之Dart 3.5 与 Flutter 3.24:革新跨平台应用开发
【Dart 3.5 与 Flutter 3.24:革新跨平台应用开发】首发于公众号“AntDream”。本文深度解析 Dart 3.5 和 Flutter 3.24 的新特性,包括空安全强化、Web 与原生互操作性增强及 Flutter GPU API 等,展示了如何提升代码质量和用户体验。
45 1
|
2月前
|
Dart 开发工具
消除Flutter doctor的警告Warning: `dart` on your path resolves to xxx/bin/dart
消除Flutter doctor的警告Warning: `dart` on your path resolves to xxx/bin/dart
32 0
下一篇
无影云桌面