[英]Flutter: Function with function as Argument; set default function
I want to create a helper to handle my dialogs.我想创建一个助手来处理我的对话框。 For this I created a static method to call: I have a class DialogInstance to provide my values, that should hold style and other dialog information.
为此,我创建了一个 static 方法来调用:我有一个 class DialogInstance 来提供我的值,它应该包含样式和其他对话框信息。
class DialogInstance {
final BuildContext context;
final String title;
final String message;
final void Function() onCancel;
final void Function() onConfirm;
final String confirmText;
final String cancelText;
final Color confirmColor;
final Color cancelColor;
DialogInstance.confirm(
{@required this.context,
@required this.title,
@required this.message,
@required this.onConfirm,
Function() onCancel, // should be default set
String confirmText,
String cancelText,
Color confirmColor,
this.cancelColor})
: this.onCancel = onCancel ?? _popContext(context), // setting default (doesn't work)
this.confirmText = confirmText ?? 'Ok',
this.cancelText = cancelText ?? 'Abbruch',
this.confirmColor = confirmColor ?? Colors.red;
static _popContext(BuildContext context) {
Navigator.pop(context);
}
}
I call this via:我通过以下方式调用它:
DialogHelper.showDialog(dialogInstance: myDialog)
If I do it like this, the method _popContext gets called at initialisation and not onPressed in the dialog.如果我这样做,方法 _popContext 会在初始化时调用,而不是在对话框中调用 onPressed。 How can I set this function as default and the dialog doesn't get closed at initialisation?
如何将此 function 设置为默认值,并且对话框在初始化时不会关闭?
Necessary to create a new function and call pop context () => _popContext(context)
.需要创建一个新的 function 并调用 pop context
() => _popContext(context)
。 But it's impossible to create final function in constructor, use factory constructor.但是不可能在构造函数中创建最终的 function,使用工厂构造函数。
class DialogInstance {
final BuildContext context;
final String title;
final String message;
final void Function() onCancel;
final void Function() onConfirm;
final String confirmText;
final String cancelText;
final Color confirmColor;
final Color cancelColor;
DialogInstance._(
{this.context,
this.title,
this.message,
this.onCancel,
this.onConfirm,
this.confirmText,
this.cancelText,
this.confirmColor,
this.cancelColor});
factory DialogInstance.confirm(
{@required BuildContext context,
@required String title,
@required String message,
@required void Function() onConfirm,
Function() onCancel, // should be default set
String confirmText,
String cancelText,
Color confirmColor,
Color cancelColor}) {
return DialogInstance._(
context: context,
title: title,
message: message,
onConfirm: onConfirm,
onCancel: onCancel ?? () => _popContext(context),
confirmText: confirmText ?? 'Ok',
cancelText: cancelText ?? 'Abbruch',
confirmColor: confirmColor ?? Colors.red,
);
}
static _popContext(BuildContext context) {
Navigator.pop(context);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.