【问题标题】:What is the meaning of `Class._()..property`?`Class._()..property` 是什么意思?
【发布时间】:2021-07-09 20:54:36
【问题描述】:

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

class CounterState {
  int counter;

  CounterState._();

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

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

【问题讨论】:

  • 谢谢。 “级联 (..) 运算符可用于通过对象发出一系列调用。”
  • 当然,欢迎您

标签: flutter dart


【解决方案1】:

级联符号 (..)

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】:

    ..这叫cascade-notation

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

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

    例子

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        1。私有构造函数

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

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

        私人飞镖概念: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.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-10
          • 2019-06-16
          • 2021-12-19
          • 1970-01-01
          • 2014-12-03
          • 2013-02-11
          相关资源
          最近更新 更多