`Class._()..property` 是什么意思?

Mak*_*leg 5 dart flutter

._()..下面的代码是什么意思?

class CounterState {
  int counter;

  CounterState._();

  factory CounterState.init() {
    return CounterState._()..counter = 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

更准确地说——这两个点..是什么意思过去._()

cre*_*not 5

级联表示法 (..)

Dart Language 教程中,您应该真正查看一下,因为它包含很多有用的信息,您还可以找到有关您提到的级联表示法的信息:

级联 (..) 允许您对同一对象进行一系列操作。除了函数调用之外,您还可以访问同一对象上的字段。这通常可以节省您创建临时变量的步骤,并允许您编写更流畅的代码。

举个例子,如果你想更新渲染对象的多个字段,你可以简单地使用级联表示法来保存一些字符:

renderObject..color = Colors.blue
    ..position = Offset(x, y)
    ..text = greetingText
    ..listenable = animation;

// The above is the same as the following:
renderObject.color = Colors.blue;
renderObject.position = Offset(x, y);
renderObject.text = greetingText;
renderObject.listenable = animation;
Run Code Online (Sandbox Code Playgroud)

当您想要在赋值或调用函数的同一行中返回对象时,它也会有所帮助:

canvas.drawPaint(Paint()..color = Colors.amberAccent);
Run Code Online (Sandbox Code Playgroud)

命名构造函数

._()是一个命名的私有构造函数。如果类未指定另一个非private构造函数(默认的或命名的),则无法从库外部实例化 该类。

class Foo {
  Foo._(); // Cannot be called from outside of this file.

  // Foo(); <- If this was added, the class could be instantiated, even if the private named constructor exists.
}
Run Code Online (Sandbox Code Playgroud)

了解有关私有构造函数的更多信息。


Rav*_*mar 3

..这称为级联表示法

级联 (..) 允许您对同一对象进行一系列操作。

除了函数调用之外,您还可以访问同一对象上的字段。这通常可以节省您创建临时变量的步骤,并允许您编写更流畅的代码。

例子

querySelector('#confirm') // Get an object.
  ..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));
Run Code Online (Sandbox Code Playgroud)