Many methods like complete
in class Completer
are marked "abstract", but in fact It can be directly invoked without being implemented. I'm really confused. Could anyone help me?
Note: Abstract methods are those methods that don't have any implementation. It should also be noted that a class in Dart can be declared abstract using the "abstract" keyword followed by the class declaration. A class that is declared using the abstract keyword may or may include abstract methods.
Interfaces and abstract classesDart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.
We cannot create the instance of an abstract class that means it can't be instantiated. It can only be extended by the subclass, and the subclass must be provided the implantation to the abstract methods which are present in the present class.
Yes, this can be a bit confusing. While abstract classes cannot be instantiated, it is possible to make them appear to be instantiable by defining a factory constructor. This is what Completer
, Future
and other abstract classes do:
abstract class Completer<T> {
factory Completer() => new _CompleterImpl<T>();
...
}
You can then invoke methods on the object created by the factory
constructor. In the example above, factory Completer()
returns a new _CompleterImpl
object. Look at the (truncated) code of that class:
class _CompleterImpl<T> implements Completer<T> {
final _FutureImpl<T> _futureImpl;
_CompleterImpl() : _futureImpl = new _FutureImpl() {}
Future<T> get future {
return _futureImpl;
}
void complete(T value) {
_futureImpl._setValue(value);
}
...
}
and you see complete()
; that is the method being invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With