[Dart] Language samples
Dart Language Samples
Dart is a client-optimized language for fast apps on any platform.
This collection is not exhaustive—it’s just a brief introduction to the language for people who like to learn by example.
Hello World
Every app has a main()
function. To display text on the console, you can use the top-level print()
function:
1 | void main() { |
Variables
Even in type-safe Dart code, most variables don’t need explicit types, thanks to type inference:
1 | var name = 'Voyager I'; |
Read more about variables in Dart, including default values, the var
, final
and const
keywords, type-safe, type inference and static types.
Control flow statements
Dart supports the usual control flow statements:
1 | if (year >= 2001) { |
Read more about control flow statements in Dart, including if
, else
, else if
, break
and continue
, switch
and case
, and assert
.
Functions
We recommend specifying the types of each function’s arguments and return value:
1 | int fibonacci(int n) { |
A shorthand =>
(arrow) syntax is handy for functions that contain a single expression or return statement. This syntax is especially useful when passing anonymous functions as arguments:
1 | flybyObjects.where((name) => name.contains('turn')).forEach(print); |
Besides showing an anonymous function (the argument to where()), this code shows that you can use a function as an argument: the top-level print()
function is an argument to forEach().
Read more about functions in Dart, including optional parameters, default parameter values, and lexical scope.
Comments
Dart comments usually start with //.
1 | // This is a normal, one-line comment. |
Read more about comments in Dart, including how the documentation tooling works.
Imports
To access APIs defined in other libraries, use import.
1 | // Importing core libraries |
Read more about libraries and visibility in Dart, including library prefixes, show and hide, and lazy loading through the deferred keyword.
Classes
Here’s an example of a class with three properties, two constructors, and a method. One of the properties can’t be set directly, so it’s defined using a getter method (instead of a variable).
1 | class Spacecraft { |
You might use the Spacecraft class like this:
1 | var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5)); |
Read more about classes in Dart, including initializer lists, optional new and const, redirecting constructors, factory constructors, getters, setters, and much more.
Inheritance
Dart has single inheritance.
1 | class Orbiter extends Spacecraft { |
Read more about extending classes, the optional @override
annotation, and more.
Mixins
Mixins are a way of reusing code in multiple class hierarchies. The following is a mixin declaration:
1 | mixin Piloted { |
To add a mixin’s capabilities to a class, just extend the class with the mixin.
1 | class PilotedCraft extends Spacecraft with Piloted { |
PilotedCraft now has the astronauts field as well as the describeCrew() method.
Read more about mixins.
Interfaces and abstract classes
Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.
1 | class MockSpaceship implements Spacecraft { |
Read more about implicit interfaces.
You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).
1 | abstract class Describable { |
Any class extending Describable has the describeWithEmphasis() method, which calls the extender’s implementation of describe().
Read more about abstract classes and methods.
Async
Avoid callback hell and make your code much more readable by using async and await.
1 | const oneSecond = Duration(seconds: 1); |
The method above is equivalent to:
1 | Future<void> printWithDelay(String message) { |
As the next example shows, async
and await
help make asynchronous code easy to read.
1 | Future<void> createDescriptions(Iterable<String> objects) async { |
You can also use async*
, which gives you a nice, readable way to build streams.
1 | Stream<String> report(Spacecraft craft, Iterable<String> objects) async* { |
Read more about asynchrony support, including async functions, Future, Stream, and the asynchronous loop (await for).
Exceptions
To raise an exception, use throw
:
1 | if (astronauts == 0) { |
To catch an exception, use a try statement with on or catch (or both):
1 | try { |
Note that the code above is asynchronous; try works for both synchronous code and code in an async function.
Read more about exceptions, including stack traces, rethrow, and the difference between Error and Exception.
Other topics
Many more code samples are in the language tour and the library tour. Also see the Dart API reference, which often contains examples.
References
[1] Language samples | Dart - https://dart.dev/samples
[2] Dart programming language | Dart - https://dart.dev/
[3] Language tour | Dart - https://dart.dev/guides/language/language-tour
[4] Library tour | Dart - (https://dart.dev/guides/libraries/library-tour