在自定义小部件颤动中使Function参数为可选
问题内容:
我尝试在构造函数中使用一些参数创建一些自定义小部件。该小部件具有一些可选的和必需的参数。如何使Function
类型参数在我的可选Widget
。
class TextInputWithIcon extends StatefulWidget {
final String iconPath;
final String placeHolder;
final Function(bool) onFocusChange;
const TextInputWithIcon(
{Key key,
@required this.iconPath,
this.placeHolder = "",
this.onFocusChange})
: super(key: key);
@override
_TextInputWithIconState createState() => _TextInputWithIconState();
}
class _TextInputWithIconState extends State<TextInputWithIcon> {
@override
Widget build(BuildContext context) {
return MY_WIDGET;
}
}
问题答案:
可选参数可以是位置参数或命名参数,但不能同时使用。
默认情况下,命名参数是可选的,因此您不必分配默认值。
const TextInputWithIcon(
{Key key,
@required this.iconPath,
this.placeHolder = "",
this.onFocusChange
})
: super(key: key);
并在调用onFocusChange
执行空检查时:
if(this.onFocusChange != null) {
this.onFocusChange(boolValue)
}
请看可选参数以更好地了解。
编辑:谢谢乔纳·威廉姆斯的澄清。