在自定义小部件颤动中使Function参数为可选 [英] Make Function parameter optional in custom widget flutter

查看:37
本文介绍了在自定义小部件颤动中使Function参数为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在构造函数中使用一些参数创建一些自定义小部件。该小部件具有一些可选的和必需的参数。如何在我的小部件中使 Function 类型参数为可选。

I try to create some custom widget with some parameter in the constructor. This widget has some optional and required parameter. how can make Function type parameter optional in my 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;
   }
}


推荐答案


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

Optional parameters can be either positional or named, but not both.

命名参数默认为可选,因此您可以

Named parameters are optional by default so you don't have to assign the default value.

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

,并在调用 onFocusChange 时执行null检查:

and when calling the onFocusChange perform a null check:

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

看看可选参数以更好地理解。

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

Thank you Jonah Williams to clarification.

这篇关于在自定义小部件颤动中使Function参数为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆