Silly question, but the dart language tour nor a web search seems to come up with anything.
How do I print a warning when a particular method is used, analogous to #warning directive in C?
If you want a warning from static analysis when a method is used, you should use the #Deprecated annotation.
For example:
#Deprecated('Call bar() instead')
void foo() {}
Related
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
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.:
https://github.com/dart-lang/sdk/blob/9a618e5661665b8d687a28e6b1ec25e9177ec2d7/sdk/lib/core/iterable.dart#L197
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.
I have a Dart class (foo.dart):
class Foo {
void talk() {
print('Hello');
}
}
After compiling foo.dart to JavaScript, I'd like to be able to use Foo like this:
var foo = new Foo(); // from foo.dart.js
foo.talk() // prints "Hello"
My questions:
Is this currently possible?
If so, how?
If not, what plans, if any, are in place to make it possible?
The dart:js library documentation states:
This library does not yet make Dart objects usable from JavaScript, their methods and proeprties [sic] are not accessible, though it does allow Dart functions to be passed into and called from JavaScript.
That word "yet" offers some hope, but I've found very little on this topic anywhere else.
Edit:
I do realize it's possible to call Dart functions from JavaScript using dart2js. However, what I'm trying to do is somewhat different. I'd like to be able to access all of the functionality of a Dart class from JavaScript.
Due to tree-shaking and minification this is normally not possible. If you have a Dart application (with a main() then you can make a Dart function available to be called from JavaScript (see How to call a Dart function from Javascript? for an example).
As far as I know there are plans to support your requirement but I have no idea about progress or when such a feature might be available.
This is the related project https://github.com/dart-lang/js-interop
In many languages if you try to instantiate abstract class you get compile time error.
In Dart however, you get warning while compiling and a runtime exception AbstractClassInstantiationError.
Why is that? Can someone provide an example, where it's reasonable to compile such code?
Dart tries to allow you to run your program while you are developing it.
That is why many things that are compile time errors in other languages are compile-time warnings and runtime errors in Dart. This includes "x is Foo" where Foo doesn't exist, type-annotating with a non-existing types, and calling constructors of partial (abstract) classes.
In short: because it's not a problem that prevents the program from being compiled (unlike a syntax error that might mean the rest of the file is interpreted wrongly), so there is no reason to stop you from running the code. Only if you hit the branch that actually depends on the problem will your program be stopped.
It appears that the answer is factory constructor in abstract class:
abstract class Foo {
factory Foo() { // make Foo appear to be instantiable
return new Bar();
}
some(); // some abstract method
Foo.name() {} just a named constructor
}
class Bar extends Foo {
Bar():super.name(); // call named super constructor
some() {} // implement abstract method
}
main() {
print(new Foo()); // "instantiate" abstract Foo
}
Output:
Instance of 'Bar'
Asking 'where it's reasonable to compile such code?' in Dart isn't very meaningful because Dart is an interpreted language - there is no compilation stage. Dart editors will issue warnings if they think you are making a type error as they analyse your code on the fly.
Factory constructors can be used to provide a 'default' concrete implementation of an abstract class as you have done in your example. This is used quite widely in Dart. For instance, if you create a new Map object you actually get a LinkedHashMap object - see this question and answer.
In your example your are not instantiating an instance of Foo ('new Foo' does not appear anywhere), you are instantiating a `Bar'. This is because when a factory constructor is called a new instance of its class is not automatically instantiated.
What does external mean in Dart? For example: external DateTime._now();
I'm new to Dart, I can't find documentation for external, so can you give an example to help explain?
9.4 External Functions
An external function is a function whose body is provided separately from its
declaration. An external function may be a top-level function (17), a method
The body of the function is defined somewhere else.
As far as I know this is used to fix different implementations for Dart VM in the browser and Dart VM on the Server.
When we make an external function inside a class like toString()
external String toString();
means this method is abstract and the child of the parent class will add the function body, that's because in Dart we only can make an abstract class.
Summary:
external function = abstract function in not abstract classes
I don't think external keyword is meant to be used to mark methods as abstract, even if that's possible
It's enough to leave a method with no implementation to set it abstract, inside an abstract class
It's the equivalent of declare in TypeScript, and extern in C#, those are used for interoperability with other runtimes, which means you're telling the compiler "Don't worry about this method's implementation, I promise it will exist at runtime", the runtime may be in C or Javascript or whatever
In case, if you are wondering why or where should I even use external keyword, here is a one more example for Flutter.
class MyStruct extends Struct {
#Int32()
external int a;
#Float()
external double b;
external Pointer<Void> c;
}
Sometimes, but not often when you play with native libraries, in this case with Struct to access native struct's field in memory. Under Struct We must declare all fields as external because it will be external fields from dart:ffi (C / C++).
So, external is more than just way to declare "abstract method".
9.4 External Functions
An external function is a function whose
body is provided separately from its
declaration.
What this does mean is that you define the function, but without implementation. It's exactly how you define the abstract method, but the only difference is that with external you don't implement the method in dart but in C or something else.
Something like String class it can be considered as external functions except that the String class it marked with #pragma('vm:entry-point') which make the entire class use native code.
See the following example to understand:
This dart's side.
https://github.com/dart-lang/sdk/blob/main/sdk/lib/core/string.dart#L711
This the implementation in C++.
https://github.com/dart-lang/sdk/blob/main/runtime/lib/string.cc#L467-#L472
In my opinion it is an equivalent of Java native keyword. For example, since current time milliseconds is implemented differently on Android, iOS, Linux etc, DateTime.now().millisecondsSinceEpoch will be linked to different implementations at runtime. So it is not initially known how this method will look like. For this reason it is marked as external meaning it is platform dependent.
Are there any plans to introduce attributes
for classes, methods, parameters of methods,
something like C# or Java attributes ?
[Test]
class SomeClass
{
[Test]
someMethod()
}
or
#Test
class SomeClass
{
#Test
someMethod(#Test int param)
}
For many frameworks it would be very useful
In dart, they are called metadata / annotation. The syntax is quite close to java. Here's a example :
#Test testMethod() {}
In Dart Specification you can read :
Metadata consists of a series of annotations, each of which begin with the character #, followed a constant expression that starts with an identifier. It is a compile time error if the expression is not one of the following:
A reference to a compile-time constant variable.
A call to a constant constructor.
[....]
Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive.
There're already some annotations predifined in dart:core. Particulary #override, #deprecated and #proxy.
Dart already has annotations, similar to Java in some ways, they're just not used in very many places yet, and they're not accessible from reflection yet either.
See this article: http://news.dartlang.org/2012/06/proposal-to-add-metadata-to-dart.html
Here's a brief introduction to the two metadata annotations currently available in the Dart meta library:
Dart Metadata is your friend.
This doesn't preclude you from using your own, but these are the two that have tooling integration with the Dart Editor.