Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract methods in Dart API reference

Tags:

dart

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?

like image 469
Zhe Chen Avatar asked Dec 01 '12 11:12

Zhe Chen


People also ask

How do you do an abstract method in darts?

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.

What is the difference between Dart's interfaces and abstract classes?

Interfaces and abstract classesDart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

Can we instantiate abstract class in Dart?

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.


1 Answers

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.

like image 52
Shailen Tuli Avatar answered Oct 09 '22 09:10

Shailen Tuli