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

时间:2019-12-24 09:32:43

标签: flutter dart

._()..在以下代码中是什么意思?

class CounterState {
  int counter;

  CounterState._();

  factory CounterState.init() {
    return CounterState._()..counter = 0;
  }
}

更准确地说-..过去的两个点._()是什么意思?

4 个答案:

答案 0 :(得分:0)

..这叫做cascade-notation

  

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

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

示例

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

答案 1 :(得分:0)

级联符号(..)

Dart Languague tour中,由于其中包含许多有用的信息,您应该真正检查一下,您还可以找到有关您提到的级联符号的信息:

  

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

作为示例,如果要更新渲染对象的多个字段,则可以简单地使用级联符号来保存一些字符:

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;

当您要在分配值或调用函数的同一行中返回对象时,它也很有帮助:

canvas.drawPaint(Paint()..color = Colors.amberAccent);

命名构造函数

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

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.
}

Learn more关于私有构造函数。

答案 2 :(得分:0)

CounterState._();是该类的命名构造函数。..被称为级联表示法。这意味着我们通过构造函数创建对象,然后将counter设置为0。 / p>

答案 3 :(得分:0)

1.私有构造函数

根据 dart 文档,您的 dart 应用程序是一个库,因此即使您为类创建私有构造函数,它也可以在整个应用程序中访问,因为它被视为库。所以,它不像其他 OOP 语言。

如果你只是想阻止类的实例化,read this article

私人的 Dart 概念:Source

与 Java 不同,Dart 没有关键字 public、protected 和 private。如果标识符以下划线 (_) 开头,则它对其库是私有的。有关详细信息,请参阅库和可见性。

根据 dart 文档

库和可见性:Source

导入和库指令可以帮助您创建模块化和可共享的代码库。库不仅提供 API,而且是一个隐私单元:以下划线 (_) 开头的标识符仅在库内部可见。每个 Dart 应用都是一个库,即使它不使用库指令。

2.级联运算符: Source

..(property) 用于初始化或更改属性的值。

据我所知,最好的用例是,如果您正在创建一个对象并且想要初始化其他无法通过构造函数初始化的属性,您可以使用它。

例如

var obj = TestClass(prop1: "value of prop 1", prop2: "value of prop 1")
                  ..prop3="value of prop 3";

// which improves the readability of the code with lesser code and less effort.

相关问题