跳到主要内容

构造函数

构造函数是用于创建类实例的特殊函数。

Dart 实现了多种类型的构造函数。除了默认构造函数外,这些函数都使用与其类相同的名称。

构造函数类型

#

生成式构造函数

#

要实例化一个类,请使用生成式构造函数。

dart
class Point {
  // Instance variables to hold the coordinates of the point.
  double x;
  double y;

  // Generative constructor with initializing formal parameters:
  Point(this.x, this.y);
}

默认构造函数

#

如果您未声明构造函数,Dart 将使用默认构造函数。默认构造函数是一个没有参数或名称的生成式构造函数。

命名构造函数

#

使用命名构造函数为一个类实现多个构造函数或提供额外的清晰度

dart
const double xOrigin = 0;
const double yOrigin = 0;

class Point {
  final double x;
  final double y;

  // Sets the x and y instance variables
  // before the constructor body runs.
  Point(this.x, this.y);

  // Named constructor
  Point.origin() : x = xOrigin, y = yOrigin;
}

子类不继承超类的命名构造函数。要创建一个具有超类中定义的命名构造函数的子类,请在子类中实现该构造函数。

常量构造函数

#

如果您的类生成不变的对象,请将这些对象设为编译时常量。要使对象成为编译时常量,请定义一个所有实例变量都设置为 finalconst 构造函数。

dart
class ImmutablePoint {
  static const ImmutablePoint origin = ImmutablePoint(0, 0);

  final double x, y;

  const ImmutablePoint(this.x, this.y);
}

常量构造函数并不总是创建常量。它们可能在非 const 上下文中被调用。要了解更多信息,请查阅关于使用构造函数的部分。

重定向构造函数

#

构造函数可能会重定向到同一类中的另一个构造函数。重定向构造函数具有空的主体。构造函数在冒号 (:) 后使用 this 而不是类名。

dart
class Point {
  double x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(double x) : this(x, 0);
}

工厂构造函数

#

当遇到以下两种实现构造函数的情况之一时,请使用 factory 关键字

  • 构造函数并不总是创建其类的新实例。虽然工厂构造函数不能返回 null,但它可能返回

    • 来自缓存的现有实例,而不是创建新实例
    • 子类型的新实例
  • 您需要在构造实例之前执行重要的工作。这可能包括检查参数或执行任何其他无法在初始化列表中处理的处理。

以下示例包含两个工厂构造函数。

  • Logger 工厂构造函数从缓存返回对象。
  • Logger.fromJson 工厂构造函数从 JSON 对象初始化 final 变量。
dart
class Logger {
  final String name;
  bool mute = false;

  // _cache is library-private, thanks to
  // the _ in front of its name.
  static final Map<String, Logger> _cache = <String, Logger>{};

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  factory Logger.fromJson(Map<String, Object> json) {
    return Logger(json['name'].toString());
  }

  Logger._internal(this.name);

  void log(String msg) {
    if (!mute) print(msg);
  }
}

像使用任何其他构造函数一样使用工厂构造函数

dart
var logger = Logger('UI');
logger.log('Button clicked');

var logMap = {'name': 'UI'};
var loggerJson = Logger.fromJson(logMap);

重定向工厂构造函数

#

重定向工厂构造函数指定对另一个类的构造函数的调用,以便在有人调用重定向构造函数时使用。

dart
factory Listenable.merge(List<Listenable> listenables) = _MergingListenable

可能看起来普通的工厂构造函数可以创建并返回其他类的实例。这将使重定向工厂变得不必要。重定向工厂有几个优点

  • 抽象类可能提供一个常量构造函数,该构造函数使用另一个类的常量构造函数。
  • 重定向工厂构造函数避免了转发器重复形式参数及其默认值的需要。

构造函数拆分

#

Dart 允许您提供构造函数作为参数而不调用它。称为拆分(当您拆分括号时),充当使用相同参数调用构造函数的闭包。

如果拆分是具有与方法接受的签名和返回类型相同的构造函数,则可以将拆分用作参数或变量。

拆分与 lambda 或匿名函数不同。Lambda 充当构造函数的包装器,而拆分是构造函数本身。

使用拆分

推荐dart
// Use a tear-off for a named constructor: 
var strings = charCodes.map(String.fromCharCode);  

// Use a tear-off for an unnamed constructor: 
var buffers = charCodes.map(StringBuffer.new);

不使用 Lambdas

不推荐dart
// Instead of a lambda for a named constructor:
var strings = charCodes.map((code) => String.fromCharCode(code));

// Instead of a lambda for an unnamed constructor:
var buffers = charCodes.map((code) => StringBuffer(code));

有关更多讨论,请观看此关于拆分的 Decoding Flutter 视频。


Dart 拆分 | Decoding Flutter

实例变量初始化

#

Dart 可以通过三种方式初始化变量。

在声明中初始化实例变量

#

在声明变量时初始化实例变量。

dart
class PointA {
  double x = 1.0;
  double y = 2.0;

  // The implicit default constructor sets these variables to (1.0,2.0)
  // PointA();

  @override
  String toString() {
    return 'PointA($x,$y)';
  }
}

使用初始化形参

#

为了简化将构造函数参数赋值给实例变量的常见模式,Dart 具有初始化形参

在构造函数声明中,包含 this.<propertyName> 并省略主体。this 关键字引用当前实例。

当存在名称冲突时,请使用 this。否则,Dart 风格会省略 this。生成式构造函数存在一个例外,您必须在初始化形参名称前加上 this

如本指南前面所述,某些构造函数和构造函数的某些部分无法访问 this。这些包括

  • 工厂构造函数
  • 初始化列表的右侧
  • 超类构造函数的参数

初始化形参还允许您初始化不可为空或 final 实例变量。这两种类型的变量都需要初始化或默认值。

dart
class PointB {
  final double x;
  final double y;

  // Sets the x and y instance variables
  // before the constructor body runs.
  PointB(this.x, this.y);

  // Initializing formal parameters can also be optional.
  PointB.optional([this.x = 0.0, this.y = 0.0]);
}

私有字段不能用作命名初始化形参。

dart
class PointB {
// ...

  PointB.namedPrivate({required double x, required double y})
      : _x = x,
        _y = y;

// ...
}

这也适用于命名变量。

dart
class PointC {
  double x; // must be set in constructor
  double y; // must be set in constructor

  // Generative constructor with initializing formal parameters
  // with default values
  PointC.named({this.x = 1.0, this.y = 1.0});

  @override
  String toString() {
    return 'PointC.named($x,$y)';
  }
}

// Constructor using named variables.
final pointC = PointC.named(x: 2.0, y: 2.0);

从初始化形参引入的所有变量都是 final 的,并且仅在初始化的变量的范围内。

要执行无法在初始化列表中表达的逻辑,请创建一个具有该逻辑的工厂构造函数静态方法。然后,您可以将计算出的值传递给普通构造函数。

可以将构造函数参数设置为可为空,并且不进行初始化。

dart
class PointD {
  double? x; // null if not set in constructor
  double? y; // null if not set in constructor

  // Generative constructor with initializing formal parameters
  PointD(this.x, this.y);

  @override
  String toString() {
    return 'PointD($x,$y)';
  }
}

使用初始化列表

#

在构造函数主体运行之前,您可以初始化实例变量。用逗号分隔初始化器。

dart
// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! {
  print('In Point.fromJson(): ($x, $y)');
}

为了在开发期间验证输入,请在初始化列表中使用 assert

dart
Point.withAssert(this.x, this.y) : assert(x >= 0) {
  print('In Point.withAssert(): ($x, $y)');
}

初始化列表有助于设置 final 字段。

以下示例在初始化列表中初始化三个 final 字段。要执行代码,请单击运行

import 'dart:math';

class Point {
  final double x;
  final double y;
  final double distanceFromOrigin;

  Point(double x, double y)
    : x = x,
      y = y,
      distanceFromOrigin = sqrt(x * x + y * y);
}

void main() {
  var p = Point(2, 3);
  print(p.distanceFromOrigin);
}

构造函数继承

#

子类,或子类,不从它们的超类或直接父类继承构造函数。如果一个类没有声明构造函数,它只能使用默认构造函数

一个类可以继承超类的参数。这些被称为超参数

构造函数的工作方式与您调用静态方法链的方式有些类似。每个子类都可以调用其超类的构造函数来初始化实例,就像子类可以调用超类的静态方法一样。此过程不“继承”构造函数主体或签名。

非默认超类构造函数

#

Dart 按以下顺序执行构造函数

  1. 初始化列表
  2. 超类的未命名、无参数构造函数
  3. 主类的无参数构造函数

如果超类缺少未命名、无参数构造函数,请调用超类中的构造函数之一。在构造函数主体(如果有)之前,在冒号 (:) 后指定超类构造函数。

在以下示例中,Employee 类构造函数为其超类 Person 调用命名构造函数。要执行以下代码,请单击运行

class Person {
  String? firstName;

  Person.fromJson(Map data) {
    print('in Person');
  }
}

class Employee extends Person {
  // Person does not have a default constructor;
  // you must call super.fromJson().
  Employee.fromJson(Map data) : super.fromJson(data) {
    print('in Employee');
  }
}

void main() {
  var employee = Employee.fromJson({});
  print(employee);
  // Prints:
  // in Person
  // in Employee
  // Instance of 'Employee'
}

由于 Dart 在之前调用构造函数之前评估超类构造函数的参数,因此参数可以是函数调用之类的表达式。

dart
class Employee extends Person {
  Employee() : super.fromJson(fetchDefaultData());
  // ···
}

超参数

#

为避免将每个参数传递到构造函数的超类调用中,请使用超初始化参数将参数转发到指定的或默认的超类构造函数。您不能将此功能与重定向构造函数一起使用。超初始化参数具有类似于初始化形参的语法和语义。

如果超类构造函数调用包含位置参数,则超初始化参数不能是位置参数。

dart
class Vector2d {
  final double x;
  final double y;

  Vector2d(this.x, this.y);
}

class Vector3d extends Vector2d {
  final double z;

  // Forward the x and y parameters to the default super constructor like:
  // Vector3d(final double x, final double y, this.z) : super(x, y);
  Vector3d(super.x, super.y, this.z);
}

为了进一步说明,请考虑以下示例。

dart
  // If you invoke the super constructor (`super(0)`) with any
  // positional arguments, using a super parameter (`super.x`)
  // results in an error.
  Vector3d.xAxisError(super.x): z = 0, super(0); // BAD

此命名构造函数尝试设置 x 值两次:一次在超类构造函数中,一次作为位置超参数。由于两者都寻址 x 位置参数,因此会导致错误。

当超类构造函数具有命名参数时,您可以将它们在命名超参数(下一个示例中的 super.y)和超类构造函数调用的命名参数(super.named(x: 0))之间拆分。

dart
class Vector2d {
  // ...
  Vector2d.named({required this.x, required this.y});
}

class Vector3d extends Vector2d {
  final double z;

  // Forward the y parameter to the named super constructor like:
  // Vector3d.yzPlane({required double y, required this.z})
  //       : super.named(x: 0, y: y);
  Vector3d.yzPlane({required super.y, required this.z}) : super.named(x: 0);
}