flutter - 使用 'cast' 方法和 'as' 关键字进行转换的区别

标签 flutter dart

在 Dart 中使用 as 进行转换有何不同?关键字并使用 cast 进行转换方法?

请看下面的例子:

import 'dart:convert';

class MyClass {
  final int i;
  final String s;

  MyClass({required this.i, required this.s});

  factory MyClass.fromJson(Map<String, dynamic> json) =>
      MyClass(s: json["s"], i: json["i"]);
}

void main() {
  const jsonString = '{"items": [{"i": 0, "s": "foo"}, {"i": 1, "s":"bar"}]}';
  final json = jsonDecode(jsonString);

  final List<MyClass> thisWorks = (json["items"] as List)
      .cast<Map<String, dynamic>>()
      .map(MyClass.fromJson)
      .toList();

  final List<MyClass> thisAlsoWorks = (json["items"] as List)
      .map((json) => MyClass.fromJson(json as Map<String, dynamic>))
      .toList();

  final List<MyClass> thisCrashes =
      (json['items'] as List<Map<String, dynamic>>)
          .map(MyClass.fromJson)
          .toList();
}

最后一次调用(使用 as 进行转换)导致异常:type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast .

我希望使用 as 进行类型转换会像使用 cast 一样工作方法而不会导致异常。

最佳答案

as 执行强制转换,在执行运行时检查后,更改对象的 static 类型。它不影响对象的身份。

集合(例如ListMapSet)提供了一个.cast 返回集合的新对象(“ View ”)的方法,该集合对每个元素 执行as 转换。

void main() {
  // `list1` is created as a `List<Object>` but happens to store only ints.
  List<Object> list1 = <Object>[1, 2, 3];

  try {
    // This cast will fail because `list1` is not actually a `List<int>`.
    list1 as List<int>;
  } on TypeError catch (e) {
    print(e); // This gets printed.
  }

  // `list2` is a `List`-like object that downcasts each element of `list1`
  // to an `int`. `list2` is of type `List<int>`.
  //
  // Note that `list2` is not a copy of `list1`; mutations to `list2` will
  // affect `list1`.
  List<int> list2 = list1.cast<int>();
  
  // `list3` is `list2` upcast to a `List<Object>`.  If a class `Derived`
  // derives from a class `Base`, then Dart also considers `List<Derived>`
  // to be a derived class of `List<Base>`, so no explicit cast is necessary.
  List<Object> list3 = list2;
  
  // `list4` is `list3` downcast to `List<int>`.  Since `list3` is the
  // same object as `list2`, and since `list2`'s actual runtime type is
  // `List<int>`, this cast succeeds (unlike `list1 as List<int>`).
  List<int> list4 = list3 as List<int>;

  print(identical(list1, list2)); // Prints: false
  print(identical(list2, list3)); // Prints: true
  print(identical(list3, list4)); // Prints: true
}

关于flutter - 使用 'cast' 方法和 'as' 关键字进行转换的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70959115/

相关文章:

flutter - Flutter block 模式中的状态不屈服

flutter - 我如何自行停止此计时器?

升级后 Flutter 不再工作

android-studio - 将 Flutter 包发布到本地 .m2 或私有(private) Nexus-Repository

ios - Flutter:无法安装应用程序,因为即使在开发者帐户上添加了 Iphone 设备的 UDID 也无法验证其完整性

laravel - 使用 Laravel 进行 Flutter FCM

dart - 如何处理在 Flutter 中搜索大型列表?

dart - flutter 没有互联网连接时如何读取本地文件?

android - 状态更改后我的变量重置

json - 使用 JSON 序列化/反序列化 Dart 的新枚举的最佳方法是什么?