Flutter: inherit from abstract stateless widget

4,348

Rather than extends, I would use implements, because ICustomWidget is an interface, not a class, except if you can give more context and/or code sample.

Here's the sample code for interface


abstract class ICustomWidget {
// or
// abstract class ICustomWidget extends StatelessWidget {
  void myProtocal();
}

class A extends StatelessWidget implements ICustomWidget {

  @override
  void myProtocal() {
    // TODO: implement myProtocal
  }

  @override
  Widget build(BuildContext context) {
     //Implementation
  }
}

class B extends ICustomWidget {
  // compilation error, `myProtocal` not implemented
  @override
  Widget build(BuildContext context) {
     //Implementation
  }
}
Share:
4,348
Little Monkey
Author by

Little Monkey

I'm just a little monkey!

Updated on December 09, 2022

Comments

  • Little Monkey
    Little Monkey over 1 year

    I have a class that has to take a custom widget. This one can have two different implementations, so I would like to have an abstract class as interface and create two other classes those extend the abstract one. So, I have:

    abstract class ICustomWidget extends StatelessWidget{}
    
    class A extends ICustomWidget{
    
      @override
      Widget build(BuildContext context) =>
         //Implementation
    }
    
    class B extends ICustomWidget {
      @override
      Widget build(BuildContext context) =>
         //Implementation
    }
    

    I want to ask if this is the right way to do this or there is another one. Thanks