[英]Dart set default value for parameter
in Flutter
framework i'm trying to set default value for parameters as borderRadius
, in this sample how can i implementing that?在
Flutter
框架中,我试图将参数的默认值设置为borderRadius
,在这个示例中我如何实现它? i get Default values of an optional parameter must be constant
error when i try to set that, for example:当我尝试设置时,我得到
Default values of an optional parameter must be constant
错误,例如:
class SimpleRoundButton extends StatelessWidget {
final BorderRadius borderRadius;
SimpleRoundButton({
}):this.borderRadius = BorderRadius.circular(30.0);
}
class SimpleRoundButton extends StatelessWidget {
final BorderRadius borderRadius= BorderRadius.circular(30.0);
SimpleRoundButton({
this.borderRadius,
});
}
class SimpleRoundButton extends StatelessWidget {
final BorderRadius borderRadius;
SimpleRoundButton({
this.borderRadius= BorderRadius.circular(30.0)
});
}
all of this samples are incorect所有这些样本都是不正确的
BorderRadius.circular()
is not a const function so you cannot use it as a default value. BorderRadius.circular()
不是 const 函数,因此您不能将其用作默认值。
To be able to set the const circular border you can use BorderRadius.all
function which is const like below:为了能够设置常量圆形边框,您可以使用
BorderRadius.all
函数,其常量如下所示:
class SimpleRoundButton extends StatelessWidget {
final BorderRadius borderRadius;
SimpleRoundButton({
this.borderRadius: const BorderRadius.all(Radius.circular(30.0))
});
@override
Widget build(BuildContext context) {
return null;
}
}
Gunhan's answer explained how you can set a default BorderRadius
. Gunhan 的回答解释了如何设置默认
BorderRadius
。
In general, if there isn't a const
constructor available, you instead can resort to using a null
default value (or some other appropriate sentinel value) and then setting the desired value later:通常,如果没有可用的
const
构造函数,您可以改为使用null
默认值(或其他一些适当的标记值),然后稍后设置所需的值:
class Foo {
Bar bar;
Foo({Bar? bar}) : bar = bar ?? Bar();
}
Note that explicitly passing null
as an argument will do something different with this approach than if you had set the default value directly.请注意,与直接设置默认值相比,使用此方法显式传递
null
作为参数会有所不同。 That is, Foo(bar: null)
with this approach will initialize the member variable bar
to Bar()
, whereas with a normal default value it would be initialized to null
and require that the member be nullable.也就是说,使用这种方法的
Foo(bar: null)
会将成员变量bar
初始化为Bar()
,而对于正常的默认值,它将被初始化为null
并要求该成员可以为空。 (In some cases, however, this approach's behavior might be more desirable.) (但是,在某些情况下,这种方法的行为可能更受欢迎。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.