以下方法如何使用为构造函数保留的“语法糖”?

问题描述

为说明我的观点,以下代码包含一个名为ColorValueChanger的方法,该方法使用this.passedIn作为可选参数。我以为这是为构造函数保留的?

class Foo extends StatefulWidget {
 final String passedIn;
 // Value passed in from its host
 ColorValueChanger({Key key,this.passedIn}) : super(key: key);
 _FooState createState() => new _FooState();
}
class _FooState extends State<Foo> {
 @override
 Widget build(BuildContext context) {
 return Text(widget.passedIn,);
 }
}

解决方法

它是一个构造函数。 听起来更像是示例中的错字。

固定代码为:

class Foo extends StatefulWidget {
 final String passedIn;
 // Value passed in from its host
 Foo({Key key,this.passedIn}) : super(key: key);
 _FooState createState() => new _FooState();
}
class _FooState extends State<Foo> {
 @override
 Widget build(BuildContext context) {
 return Text(widget.passedIn,);
 }
}