Reputation: 6157
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
Upvotes: 10
Views: 7882
Reputation: 1
I would recommend to do next
abstract class ICustomWidget implements Widget {
void myProtocol();
}
and rest is like previous commentator. The reason why is that you can use you interface directly in some other build method without casting it to exact type because it is already inherits Widget
Upvotes: 0
Reputation: 4866
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
}
}
Upvotes: 14