[英]Dart: Error: Setter not found (when defining constructor of a class)
I get the following error with this very simple constructor: 我用这个非常简单的构造函数收到以下错误:
class MyHomePage extends StatefulWidget {
MyHomePage(String title, String lang, {Key key}) {
this.title = title;
this.lang = lang.substring(0,2).toLowerCase();
super(key: key);
}
final String title;
final String lang;
@override
_MyHomePageState createState() => _MyHomePageState();
}
The error message: 错误信息:
Compiler message:
lib/main.dart:34:10: Error: Setter not found: 'title'.
this.title = title;
^^^^^
lib/main.dart:35:10: Error: Setter not found: 'lang'.
this.lang = lang.substring(0,2).toLowerCase();
^^^^
lib/main.dart:36:5: Error: Can't use 'super' as an expression.
To delegate a constructor to a super constructor, put the super call as an initializer.
super(key: key);
^
lib/main.dart:34:10: Error: The setter 'title' isn't defined for the class 'MyHomePage
Why is that? 这是为什么? I don't understand what that mean. 我不明白那是什么意思。 Is there a comprehensive explanation about how to define constructors in dart? 关于如何在dart中定义构造函数,是否有全面的解释? I couldn't find one on the dart.dev site. 我在dart.dev网站上找不到。
Edit: After editing the code to the following: 编辑:将代码编辑为以下内容之后:
class MyHomePage extends StatefulWidget {
MyHomePage(String title, String lang, {Key key}) {
title = title;
lang = lang.substring(0,2).toLowerCase();
super(key: key);
}
final String title;
final String lang;
@override
_MyHomePageState createState() => _MyHomePageState();
}
I have the following complaints from the compiler: 我收到编译器的以下投诉:
Compiler message:
lib/main.dart:36:5: Error: Can't use 'super' as an expression.
To delegate a constructor to a super constructor, put the super call as an initializer.
super(key: key);
^
lib/main.dart:39:16: Error: Final field 'title' is not initialized.
Try to initialize the field in the declaration or in every constructor.
final String title;
^^^^^
lib/main.dart:40:16: Error: Final field 'lang' is not initialized.
Try to initialize the field in the declaration or in every constructor.
final String lang;
There is special syntax for initialising final
variables in a constructor, answered here: 在构造函数中有用于初始化final
变量的特殊语法,请在此处回答:
https://stackoverflow.com/a/42864979/64435 https://stackoverflow.com/a/42864979/64435
Using this syntax, the working code is: 使用此语法,工作代码为:
class MyHomePage extends StatefulWidget {
MyHomePage(String title, String lang, {Key key})
: this.title = title,
this.lang = lang.substring(0, 2).toLowerCase(),
super(key: key);
final String title;
final String lang;
@override
_MyHomePageState createState() => _MyHomePageState();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.