Flutter: Optional method implementation in child class

460

You can achieve the required behaviour in two ways :

First :

abstract class A {
  void method1();

  void method2();
  
  void method3 () {
    //default implmentation or empty body
  }
}

class B extends A {
  @override
  method1() {}

  @override
  method2() {}
}

Second :

abstract class A {
  void method1();

  void method2();
}

abstract class A1 extends A {
  void method3();
}

class B extends A1 {
  @override
  method1() {}

  @override
  method2() {}
}

This way you only get warning when you're class extends A1 class without implementing method3().

Share:
460
Cyrus the Great
Author by

Cyrus the Great

Updated on December 27, 2022

Comments

  • Cyrus the Great
    Cyrus the Great over 1 year

    I have abstract class . Inside A class I have for example 3 methods:

    abstract class A {
     @protected
     void method1()
    
     @protected
     void method2()
    
     @protected
     void method3()
    }
    

    Now,Class B is extended from A:

    class B extends A {
    @override
    method1(){}
    
    @override
    method2(){}
    
    @override
    method3(){}// be optional 
    }
    

    I want to not force class B to implement all protected method in class A. For example I want to child class forced to implement 2 methods of 3 methods of class A and one method be obtional.

    How can I implemented on flutter?

  • Cyrus the Great
    Cyrus the Great over 3 years
    It is not possible to not shown method3() in child class? Means If needed then method3() overrided @EduardHasanaj
  • Cyrus the Great
    Cyrus the Great over 3 years
    I used first way. Thanks.
  • Eduard Hasanaj
    Eduard Hasanaj over 3 years
    No it is not possible to hide it completely. However you may decompose class A in classes that represents method1, method2, method3 and use implements to not extend but use their interface. @sayreskabir