skip to Main Content

I get the following error

The 'super' keyword can't be used in an extension because an extension doesn't have a superclass.

With this code,

class Animal {
  final String name;

  Animal({required this.name});

  void jump() {
    print("Jumping");
  }
}

class Dog extends Animal {
  final String breed;

  Dog({required this.breed, required super.name});
}


extension DogExtension on Dog {
  void jump() {
    super.jump();
    print("and Waving Tail");
  }
}

I can’t simply override the method in the class Dog directly instead of using an extension because class Dog is auto generated by a code generator.

Also, I don’t want to simply rename jump in the extension to jumpDog, because Dog will have it’s own inherited class, I’d like to use jump for all.

2

Answers


  1. Answer to the direct question, you can’t use super keyword inside extension. Extension is not really a class hence not really a sub-class to be able to use the super keyword. It’s more like a additional part you can fit on to a class.

    Secondly, even if you call the jump method inside the extension with this keyword as following code, it’ll only call the jump method derived from the super class of Dog.

    extension DogExtension on Dog {
      void jump() {
        this.jump();
        print("and Waving Tail");
      }
    }
    

    Which primarily means the jump() method inside the DogExtension is never called.

    If you’re seriously willing to override the Dog class’s jump method you should try considering mixins.

    class Dog extends Animal with DogMixin {
      final String breed;
    
      Dog({required this.breed, required super.name});
    }
    
    mixin DogMixin {
      void jump() {
        print('and Waving Tail');
      }
    }
    
    void main(List<String> args) {
      final dog = Dog(breed: "Husky", name: "Tom");
      dog.jump();
    }
    

    Now the dog.jump() call will invoke the overridden method from DogMixin.

    Hope this helps.

    Login or Signup to reply.
  2. you can’t use extension to override other class : https://github.com/dart-lang/language/issues/1127

    I can’t simply override the method in the class Dog directly instead
    of using an extension because class Dog is auto generated by a code
    generator.

    if you no macros, no code gen, you can’t do this case ,you only can do is :

    1. class Dog2 extends Dog{ jump(){} }
    2. extension type Dog2(Dog dog) implements Dog{jump(){}}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search