首页 > 解决方案 > 以下方法怎么可能使用为构造函数保留的“语法糖”?

问题描述

为了说明我的观点,以下代码包含一个名为 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,);
 }
}

标签: classflutteroopdartconstructor

解决方案


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

固定代码是:

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,);
 }
} 

推荐阅读