我try 在构造函数中创建一些带有参数的自定义小部件.这个小部件有一些可选的和必需的参数.

如何在my Widget中 Select Function类型参数.

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;
   }
}

推荐答案

可选参数可以是位置参数,也可以是命名参数,但不能同时是位置参数和命名参数.

默认情况下,命名参数是可选的,因此您不必指定默认值.

如果参数是可选的,但不能为空,请提供default value.

With null safety

class TextInputWithIcon extends StatefulWidget {
  final String iconPath;
  final String placeHolder;
  final Function(bool)? onFocusChange; // nullable and optional
  
  const TextInputWithIcon(
      {Key? key,
      required this.iconPath, // non-nullable and required
      this.placeHolder = "", // non-nullable but optional with a default value
      this.onFocusChange, // nullable and optional
      })
      : super(key: key);

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

}

Without null safety

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

用法:

void _focusChanged(bool value) {

    // using null-aware operator (for both with and without null safety)
    onFocusChange?.call(value);
    
    // or without null-aware operator 
    
    // with null safety
    if(onFocusChange != null) {
      onFocusChange!(value);
    }

    // without null safety
    if(onFocusChange != null) {
      onFocusChange(value);
    }

  }

请看一下Optional Parameters,以便更好地了解.

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

Flutter相关问答推荐

ListView内的ListView正在一次构建所有项目

如何在flutter文本字段中添加要点条目?

build_runner显示错误没有为类ClassDeclaration定义getter宏关键字'

如何在2024年使用Ffltter将用户数据保存在云FireStore中?

Flutter 文件拾取器Android SingleInstance模式它返回的文件路径为空

Flutter :执行com.android.build.gradle.internal.tasks.MergeNativeLibsTask$MergeNativeLibsTaskWorkAction时出现故障

FittedBox叠加技术在Flutter 中的应用

Flutter如何将2个以上的值传递到ListView上的另一个屏幕?

使用现有Map方法对子类克隆方法的逻辑进行Dart标准化

如何在Flutter 中使用选定的键和值从 map 列表创建 map

为 flutter app/firebase 保存 chatgpt api-key 的正确方法是什么

获取通过列表呈现的相同 TextEditingController 的值

是否有可能减少代码的编写,例如:ref.read(countProvider.notifier) - 在构建方法中?

graphql_flutter 错误:非抽象类GraphQLWebSocketChannel缺少实现

Cloud firestore:如何使用 map 对象创建和更新嵌套数组

如何流畅切换画面?

String类型不是Widget类型的子类型?在dart 中

Flutter 如何使用 ClipPath 编辑容器的顶部?

如何在 flutter 中制作这种类型的扩展瓦片

如何在 flutter 中更改日期 Select 器 colored颜色 ?