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

Sam*_*man 8 dart 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;
   }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 8

您可以使用不执行任何操作的默认值:

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 = _dummyOnFocusChange})
      : assert(onFocusChange != null), super(key: key);

  @override
  _TextInputWithIconState createState() => _TextInputWithIconState();

  static dynamic _dummyOnFocusChange(bool val) {}
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个静态命名函数,而不仅仅是一个闭包作为默认值,因为闭包不是 const 并且当前默认值需要是 const。

我添加了assert(...)以确保在null显式传递时显示错误。


Uma*_*r M 6

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

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

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

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

if(this.onFocusChange != null) {
    this.onFocusChange(boolValue)
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 默认情况下,命名参数是可选的 (2认同)

小智 5

如果您不喜欢命名参数(如我 :/),另一种选择是:

function_name (argument1, [argument2]) {
   // statements
}
Run Code Online (Sandbox Code Playgroud)

括号中的参数是可选的。

来源