flutter 为什么Map和List是可示例化的,但它们在dart中却是抽象类

beq87vna  于 2023-03-19  发布在  Flutter
关注(0)|答案(2)|浏览(120)
List list = List();
Map map = Map();

示例化List抽象类和Map抽象类的原因是什么?它们被认为是抽象的

z9zf31ra

z9zf31ra1#

这是因为它们使用工厂构造函数。
使用factory关键字,可以将构造函数重定向到接口的另一个实现。
因此,我们可以写:

abstract class Something {
  factory Something() = _ConcreteSomething;

  void someMethod();
}

class _ConcreteSomething implements Something {
  @override
  void someMethod() { }
}
mbyulnm0

mbyulnm02#

好了,看看dart SDK中的列表构造函数,我们有这个(和其他一些):

@Deprecated("Use a list literal, [], or the List.filled constructor instead")
external factory List([int? length]);  // List();

external factory List.filled(int length, E fill, {bool growable = false}); // List.filled();

是的,它们是dart中的 abstract 类,但是它们的构造函数实现(就像上面代码中的两个构造函数一样)不是用dart代码编写的,而是用其他地方(本机代码,C++)编写的,因此使用了external关键字。
如果不使用external关键字,而只使用factory关键字,则必须返回其现有示例或重定向到dart中派生类的示例。

相关问题