私は構文上または実際に何か間違ったことをしている可能性があるので、「それをしないでください」は有効かもしれませんが、これはうまくいくはずです:
class Thing {
//static dynamic noop = () { }; // fails
static dynamic noop = ([dynamic value]) { }; // works for null cases
dynamic _callback;
Thing._([dynamic callback([dynamic value])])
: this._callback = callback != null ? callback : Thing.noop;
factory Thing([dynamic callback([dynamic value])]) {
return new Thing._(callback);
}
}
これらのテストを実行すると、最初のテストは失敗しますが、2 番目、3 番目、4 番目のテストは成功します。
//Caught type '() => dynamic' is not a subtype of type '([dynamic]) => dynamic' of 'callback'.
test('callback with optional param', () {
var thing = new Thing(() { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing(([_]) { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing();
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing(null);
thing.doCallback();
thing.doCallback('data');
});