Dart类型转化-服务器数据转Model

如果 map['userId'] 是一个 int 类型,而你试图将它通过 as String? 转换为 String? 类型,会抛出一个 TypeError。因为 int 类型不能直接转换为 String? 类型。

示例

Map<String, dynamic> map = {
  'userId': 12345, // 这个值是一个 int
};

String? userId = map['userId'] as String?; // 这里会抛出一个 TypeError

运行时的情况

在运行时,当 Dart 试图将 int 类型的值(如 12345)转换为 String? 时,会检测到类型不匹配,并抛出 TypeError。错误信息大致如下:

TypeError: type 'int' is not a subtype of type 'String?' in type cast

避免错误的方法

为了避免这种错误,可以在转换之前检查类型,或者将 int 转换为 String

1. 使用类型检查

var value = map['userId'];
if (value is String) {
  String? userId = value;
} else if (value is int) {
  String? userId = value.toString(); // 将 int 转换为 String
}

2. 使用 toString() 方法

如果你知道 map['userId'] 可能是 int,可以直接调用 toString()

String? userId = map['userId']?.toString();

这种方式将任何非空的 map['userId'] 值转换为 String?,无论它最初是 int 还是 String

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容