在dart和flutter代码中,通常在类的参数/实例变量之前声明构造函数,例如:
class Example {
// Constructor BEFORE parameters
Examples(this.name, this.profession);
final String name;
final String profession;
}
Run Code Online (Sandbox Code Playgroud)
来自php,我习惯了不同的顺序,即:参数优先:
class Example {
final String name;
final String profession;
Examples(this.name, this.profession);
}
Run Code Online (Sandbox Code Playgroud)
(据我所知,这也是用我的其他语言完成的,例如Java,Ruby,C#...)
在Dart的编码样式指南中,https://dart.dev/guides/language/effective-dart/style没有解决此“现象”,并且到目前为止,我没有找到其他有关此现象的资料。
这是“ Cloud Next '19”演示文稿中的一个示例,由flutter核心开发人员提供了代码:
https://youtu.be/RpQLFAFqMlw?t=1070
甚至当通过创建新的flutter项目时,您获得的即用型计数器应用程序也flutter create使用以下顺序:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
Run Code Online (Sandbox Code Playgroud)
有人知道,为什么Dart选择不同的方式?
小智 6
关于构造函数,Flutter 风格指南与Dart 风格指南不同,这两个指南在其他方面有很多共同点。因此,虽然 Dart 的风格指南确实没有提到“构造函数优先”之类的内容,也没有任何代码示例给人留下这样的建议的印象,但 Flutter 已经提出了自己的风格指南,正如 DaGardner 之前提到和链接的那样。原因是有些小部件带有大量参数,这似乎是特定于 flutter 的。
进一步的讨论可以在以下位置找到: https://github.com/flutter/flutter/issues/1220 https://github.com/dart-lang/linter/issues/186
这只是Flutter团队使用的一种样式约定,并在其样式指南中进行了说明。
做出此决定的主要原因是:
这可以帮助读者一目了然地确定该类是否具有默认的隐式构造函数。
并进一步
如果构造函数可能在类中的任何位置,那么读者将不得不检查类的每一行,以确定是否存在隐式构造函数。
对于其他元素,例如成员,方法,静态字段等,在flutter样式指南中没有定义明确的顺序:
类的方法,属性和其他成员应按顺序排列,以帮助读者理解类的工作方式。
但是,如果没有明显的顺序,则样式指南会建议以下内容:
- 构造函数,首先使用默认构造函数。
与类相同类型的常量。
返回与类相同类型的静态方法。
从构造函数设置的最终字段。
其他静态方法。
静态属性和常量。
可变属性,每个属性在订单获取程序,私有字段,设置程序中,没有换行符分隔它们。
只读属性(hashCode除外)。
运算符(==除外)。
方法(除了toString和build)。
Widget和State类的构建方法。
运算符==,hashCode,toString和与诊断相关的方法,按此顺序。
所有引号直接取自样式指南。
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |