Flutter: inherit from abstract stateless widget

末鹿安然 提交于 2021-02-19 03:18:43

问题


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


回答1:


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
  }
}


来源:https://stackoverflow.com/questions/54946036/flutter-inherit-from-abstract-stateless-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!