The question is not that simple as you may think and the answer depends on what you want to achieve.
If you want to override something before the super implementation is executed then you call super after you override what you want to override. For example:
class DoTheMathAndPrint {
int first = 1;
int second = 2;
void iWillDoTheMathAndPrint() {
int sum = first + second;
print("The sum is $sum");
}
}
class NoIWillDoTheMath extends DoTheMathAndPrint {
@override
void iWillDoTheMathAndPrint() {
first = 3;
second = 5;
super.iWillDoTheMathAndPrint();
// will print The sum is 8;
}
}
If you want the normal flow and then "extend" the flow you will call super first then you'll execute your code. For example:
class WellIHateMath extends DoTheMathAndPrint {
@override
void iWillDoTheMathAndPrint() {
super.iWillDoTheMathAndPrint();
print("I hope it printed $3");
}
}
Now, what I usually do when i work with subclasses of frameworks (Flutter, Android, iOS), i decide if a method is "constructive" or "destructive". The "constructive" methods would be some that initialise pieces of code, configurations etc (like initState
in flutter). For this kind of methods I call super first, I want to be sure that everything is set up by the framework then I can do my things.
For "destructive" methods, the kind that clean up the resources, free memory etc, (like dispose()
in flutter) i call super last, I free my resources then I can say to the framework: "all good, do your job".
There is one thing in dart, that it was a shock for me (because I didn't read enough), is the super call when you use mixins. You have to be very careful with this, the super
won't be called on the super class, it will be called on the mixin. For example:
class SomeAwesomeState<T extends StatefulWidget> extends State<T> {
List<SomeBigObject> _theList = ...smething big;
@override
void dispose() {
_theList.clear();
super.dispose();
}
}
class MyStateWithAnimation extends SomeAwesomeState<AnimationWidget> with SingleTickerProviderStateMixin {
// some awesome animations here
@override
void dispose() {
//remove whatever here
super.dispose(); => this will be the super on the SingleTickerProviderStateMixin not on the SomeAwesomeState
}
}