Reputation: 105
I would like to understand how built in methods work in Dart, therefore i would like to access the source code, any idea how to access a source code of built in methods? below is an example of one method map() enter image description here
Upvotes: 1
Views: 638
Reputation: 31299
Well, it can be a little complicated to find the concrete implementation of all methods. There are several reasons for that:
Some implementations are different for Dart running as JavaScript and Dart running on the Dart VM.
Some methods are heavily dependent on C++ code for the Dart VM implementation.
Lots of classes in Dart are just interfaces like the Iterable
which means the Iterable.map
method can have different implementations for e.g. lists and maps.
However, all of the source code can be found in the GitHub repository if you browse through the code. But it takes some experience to know where to look for things:
https://github.com/dart-lang/sdk/tree/stable
So if we e.g. want to look for the default map
method in Iterable
we need to see if there are a default implementation. We can find the class here in the repo.:
Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
By searching for class MappedIterable
we can see this class is implemented in:
https://github.com/dart-lang/sdk/blob/stable/sdk/lib/internal/iterable.dart#L354
class MappedIterable<S, T> extends Iterable<T> {
final Iterable<S> _iterable;
final _Transformation<S, T> _f;
factory MappedIterable(Iterable<S> iterable, T function(S value)) {
if (iterable is EfficientLengthIterable) {
return new EfficientLengthMappedIterable<S, T>(iterable, function);
}
return new MappedIterable<S, T>._(iterable, function);
}
MappedIterable._(this._iterable, this._f);
Iterator<T> get iterator => new MappedIterator<S, T>(_iterable.iterator, _f);
// Length related functions are independent of the mapping.
int get length => _iterable.length;
bool get isEmpty => _iterable.isEmpty;
// Index based lookup can be done before transforming.
T get first => _f(_iterable.first);
T get last => _f(_iterable.last);
T get single => _f(_iterable.single);
T elementAt(int index) => _f(_iterable.elementAt(index));
}
One details you will see is that a lot of the SDK are duplicated right now in a sdk and sdk_nnbd version. This is temporarily while the Dart team are implementing the non-nullable by default feature and is not used unless you are running with this feature turned on.
Upvotes: 2