在flutter任何人清楚地解释我的困惑key,代码如下
MyHomepage({Key key, this.title}) : super(key: key);
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 13
代码是MyHomepage小部件的构造函数.
{Key key, this.title}
Run Code Online (Sandbox Code Playgroud)
声明2个可选的命名参数(可选命名因为{})where
第一个是Key` key类型的名称Key`
the 2nd is of name title带有字段类型的名称,this.title并this.title使用传递的值自动初始化这是一个很好的语法糖,可以节省一些写作.
:启动初始化列表.初始化列表允许一些人在将调用转发给超类的构造函数之前执行一些表达式.
初始化类时,this禁止读取访问权限,直到完成对超级构造函数的调用(直到执行构造函数的主体 - 在您的示例中,构造函数没有主体).
初始化列表通常用于验证传递的参数值,assert(key != null)或者final使用计算值初始化字段(final以后无法初始化或更新字段).
super(key: key)转发到超类的构造函数,并将传递给的参数key传递给MyHomepagesuper constructors key参数(与for相同MyHomepage({Key key})).
小智 6
Thanks for @Günter's detailed explanation which helped me at the very beginning. Here I would like to explain the background for this question, and especially the punctuations as syntax a little bit.
The mentioned line of code:
MyHomepage({Key key, this.title}) : super(key: key);
Run Code Online (Sandbox Code Playgroud)
should come from the auto-generated flutter application boilerplate.
The complete context is:
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)
For me, the weired punctuations (curly brackets{ } and two colons :) are what prevented me from comprehending its syntax.
Curly brackets of {Key key, this.title}: is the syntax for declaring optional parameters while defining function in Dart.
The 1st Colon of MyHomepage(...) : super(key: key) is a separator that specifies the initializer list (super(key: key)) of constructor function MyHomepage(...)
The 2nd Colon within super(key: key) is the way how you pass parameter to a named function ( super() in this case ).
enableFlags is defined as followingvoid enableFlags({bool bold, bool hidden}) {...}
Run Code Online (Sandbox Code Playgroud)
parameterName before value, seperated with colon :, which is safer for developer than pythononic way. The counterpart syntax in swift should be external parameter.enableFlags(bold: true, hidden: false);
Run Code Online (Sandbox Code Playgroud)
Wish this could help.
All the definitions and examples can be found at Dart's official document
| 归档时间: |
|
| 查看次数: |
3896 次 |
| 最近记录: |