Defining class requirements via abstract classes in Dart / Flutter
If you want to use something akin to Swift’s protocols in Dart, you have the option to define abstract
classes. While defining methods is well documented and pretty straightforward, properties can be a bit more tricky.
Defining required methods
Let’s use an old Elvis song to illustrate how this works…
abstract class Lovable {
// Add me to loved items; must have a bool parameter
loveMe(bool tender, bool sweet); // Remove me from loved items
unloveMe();
}
All that is simple enough. Once you create a class you can specify that it implements the above:
class Darling implements Lovable {
// Here you will be required to implement all Lovable methods!
}
So far, so good!
Defining required properties
But if we try a similar approach with properties and simply add an isLoved
boolean property we will get the following error:
Non-nullable instance field ‘isLoved’ must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it, or mark it ‘late’.
Usually initializing it makes no sense in this context. On the other hand if you mark it with late
, the error on the abstract class will go away, but now Darling
might get the following error (this can happen if you only have a getter or you’ve set the required property to final
):
Missing concrete implementation of 'setter Darling.isLoved'.
So, instead we need to define our required properties as separate getter methods and — if needed — setter methods:
abstract class Lovable { // ... // This will require at least a read-only value
bool get isLoved; // ...and the following will require write access
set isLoved(bool isLoved);
}
Of course adding a setter requirement is completely optional. If you will have final
properties or just read-only getter properties, you should only specify a get
property in your abstract class requirements. In our example, it is quite likely that isLoved
should be read-only (given that there are already methods for loving and unloving) — therefore we would not specify a setter requirement in Lovable
.