Skip to content
Advertisement

How to implement interface in-line instead of using a class in Dart/Flutter?

Is there any way to implement an interface in dart/flutter without having to use a class?

Currently, how I implement it is with the code below

JavaScript

However, I would like to implement these interface methods without having to use a class, just as I would in java. Something that would look like the code below.

JavaScript

Advertisement

Answer

There is no such feature in Dart. In order to implement an interface, you have to declare a class.

The alternatives is to define the API to accept individual functions instead of a single object, or to declare a helper class which takes the behavior of the necessary methods as constructor arguments.

Example:

JavaScript

Then you can call it as:

JavaScript

It’s not as pretty as Java, admittedly.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement