Search code examples
flutterdartclassmethodsoverriding

How to override a method and keep its original code in Dart / Flutter?


i'd like to override the method "dispose" by adding a function in it (let's imagine print()), but i'd like to keep its original purpose because otherwise it sometimes throws parent stability errors. How can I do it ?


Solution

  • You can use the super to run inherited parent class method:

    class A {
      a() {
        print("a");
       }
     }
    
    class B extends A {
      @override
      a() {
        super.a();
        print("b");
       }
     }
    

    now running B().a():

     B().a();
    
     // output:
     a
     b