Try it out yourself
You can try writing Dart code directly in your browser on this website. But note that it does not support all features, for example, user input. Alternatively, you can install Dart SDK, and run
dart filename.dart in the terminal to launch your code.
Dart uses syntax similar to C to define functions. Every app has an entry point – the
main() function. You can print out messages using
print() function. See this example:
You can use either strong or dynamic types in Dart. Strong means you have to choose variable type at declaration time and it does not change, but with dynamic typing, it can hold values of any type. By default, all variables a strongly typed, even if you do not write any specific type. To make them dynamic,
dynamic keyword is used. Look at the following example:
The basic types of variables in Dart are:
int, double, bool, String, List, Set, Map, Runes and Symbol.
You can use the same control flow structures you have seen in many other languages, such as
if, for, while:
Control flow statements such as
continue, break, switch and case are also supported.
Comments in Dart work exactly like in C or JS:
Dart supports importing libraries and
.dart files using the
Dart also supports something called deferred imports. These imports are loaded on demand: you may want to use them when you do not always have to use a certain library:
Dart supports classes and most of the OOP paradigms. Here is a sample definition of a class:
You can implement inheritance using the
extends keyword. Keep in mind that a class can only inherit one class, multiple inheritance is not supported.
To simply reuse some common code without the overhead of inheritance, you can use mixins. You create a mixin and later attach it to classes using
with keyword. Consider this example:
Instead of interfaces, Dart uses inheritance. All classes implicitly define an interface so it is sufficient to inherit the class:
You can define abstract classes with the
abstract keyword and they work pretty much like you expect:
Future is Dart’s version of JS Promises, by the way.
I hope you find this tutorial useful. If you want to learn more, Dart’s documentation is a good place to start.