There is no good way to do that. The proper thing to do is to create a forwarding class that implements the base interface:
class ForwardingA implements A {
A a;
ForwardingA(this.a);
@override
void functionA() {
shouldRunFirstFunction();
doOtherThings();
}
...
}
And that way you can be sure that you override all of the members of A
(if you don't, you will get a compile-time error).
You probably could implement some code-generation solution that, given a class A
, generates ForwardingA
for you. However, that probably would be way more work, especially if you're doing this for a small number of cases.
Another approach would be to make noSuchMethod
forward method calls to a delegate semi-automatically:
class A {
void functionA() {
print('A');
}
void functionB() {
print('B');
}
}
class ForwardingA implements A {
void Function() preamble;
A a;
late final _methods = <Symbol, Function>{
#functionA: a.functionA,
#functionB: a.functionB,
};
ForwardingA(this.a, this.preamble);
@override
dynamic noSuchMethod(Invocation invocation) {
var f = _methods[invocation.memberName];
if (f != null) {
preamble();
return Function.apply(
f,
invocation.positionalArguments,
invocation.namedArguments,
);
}
return super.noSuchMethod(invocation);
}
}
void main() {
var foo = ForwardingA(A(), () => print('Hello world!'));
foo.functionA();
foo.functionB();
}
which prints:
Hello world!
A
Hello world!
B
However, I would not recommend that since:
noSuchMethod
will incur a runtime performance penalty.
- It isn't fully automatic. You need to manually build the
Symbol
-to-Function
Map
. Worse, there would be no compile-time protection if you accidentally omit listing one of A
's members or make a typo for one of its Symbol
s.