下面的代码中._()..
是什么意思?
class CounterState {
int counter;
CounterState._();
factory CounterState.init() {
return CounterState._()..counter = 0;
}
}
更准确地说 - 过去._()
..
这两个点是什么意思?
级联表示法(..(
在Dart Languague之旅中,您应该真正查看它,因为它包含许多有用的信息,您还可以找到有关您提到的级联符号的信息:
级联 (..( 允许您对同一对象进行一系列操作。除了函数调用之外,您还可以访问同一对象上的字段。这通常可以节省您创建临时变量的步骤,并允许您编写更流畅的代码。
例如,如果要更新渲染对象的多个字段,只需使用级联表示法来保存一些字符:
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);
命名构造函数
._()
是一个命名的私有构造函数。如果类未指定另一个非私有构造函数(默认或命名(,则无法从库外部实例化该类。
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.
}
详细了解私有构造函数。
CounterState._();
是类的命名构造函数,..
称为级联表示法。意味着我们通过构造函数创建对象,然后将counter
设置为 0。
..
这称为级联表示法
级联 (..( 允许您对同一对象进行一系列操作。
除了函数调用之外,您还可以访问同一对象上的字段。这通常可以节省您创建临时变量的步骤,并允许您编写更流畅的代码。
例
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
1. 私有构造函数
根据 dart 文档,您的 dart 应用程序是一个库,因此即使您为类创建私有构造函数,它也可以在整个应用程序中访问,因为它被视为库。因此,它不像其他OOP语言。
如果您只想防止类的实例化,请阅读本文
私人飞镖概念:来源
与Java不同,Dart没有关键字public,protected和private。如果标识符以下划线 (_( 开头,则它是其库专用的。有关详细信息,请参阅库和可见性。
根据飞镖文献
库和可见性:来源
导入和库指令可以帮助您创建模块化且可共享的代码库。库不仅提供 API,而且是一个隐私单元:以下划线 (_( 开头的标识符仅在库中可见。每个 Dart 应用程序都是一个库,即使它不使用库指令。
2. 级联运算符:来源
..(财产(用于初始化或更改属性的值。
根据我的说法,最好的用例是,如果您正在创建一个对象并且想要初始化无法通过那里的构造函数初始化的其他属性,则可以使用它。
例如
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.
<小时 />