小编典典

在自定义小部件颤动中使Function参数为可选

flutter

我尝试在构造函数中使用一些参数创建一些自定义小部件。该小部件具有一些可选的和必需的参数。如何使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;
   }
}

阅读 260

收藏
2020-08-13

共1个答案

小编典典

可选参数可以是位置参数或命名参数,但不能同时使用。

默认情况下,命名参数是可选的,因此您不必分配默认值。

const TextInputWithIcon(
      {Key key,
      @required this.iconPath,
      this.placeHolder = "",
      this.onFocusChange
})
      : super(key: key);

并在调用onFocusChange执行空检查时:

if(this.onFocusChange != null) {
    this.onFocusChange(boolValue)
}

请看可选参数以更好地了解。

编辑:谢谢乔纳·威廉姆斯的澄清。

2020-08-13