如何解决如何将静态变量转换为常量并将其传递给期望最终值的类构造函数
出现以下代码错误
Cannot invoke a non-'const' constructor where a const expression is expected.
Try using a constructor or factory that is 'const'.
static const MyClass darkerText = MyClass(param);
了解到在这种情况下使用static
可能是不合适的。只是想看看是否有任何可能的方法。
class MyClass {
final int total;
MyClass(total);
}
class Test {
static int param = 10;
static const MyClass darkerText = MyClass(param);
}
main() {
new Test();
}
解决方法
您似乎误解了function test(){
$driver = new WebDriver("localhost","4444");
$driver->connect("chrome");
$driver->get("google.com");
}
function send(){
$diver->get("facebook.com");
}
和const
的观点。 final
用于编译时已知的值,因此,在您的情况下,如果所有值都是编译时常数,则可能没有意义,
const
更常见的做法是使用class MyClass {
final int total;
const MyClass(this.total);
}
class Test {
static const int param = 10;
static const MyClass darkerText = MyClass(param);
}
main() {
new Test();
}
变量,这些变量可以在程序的生命周期中进行设置,但在设置后不会更改,在这种情况下,您将使用以下方式:
final
,
您可以在DartPad中复制粘贴运行完整代码
您需要使用this.total
并删除const
的{{1}}关键字
darkerText
,
如错误所示,您的MyClass
是非常量构造函数。将其设为const:
class MyClass {
final int total;
const MyClass(this.total);
}
class Test {
static const int param = 10;
static const MyClass darkerText = MyClass(param);
}
void main() {
new Test();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。