Language samples

A comprehensive tour, with examples, of the Dart language. Most of the read more links in this page point to the language tour.

Library tour

An example-based introduction to the Dart core libraries. See how to use the built-in types, collections, dates and times, streams, and more.

Every app has a function.To display text on the console, you can use the top-level print() function:

Variables

Even in type-safe Dart code, most variables don’t need explicit types,thanks to type inference:

  1. var name = 'Voyager I';
  2. var year = 1977;
  3. var antennaDiameter = 3.7;
  4. var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
  5. var image = {
  6. 'tags': ['saturn'],
  7. 'url': '//path/to/saturn.jpg'
  8. };

Read more about variables in Dart, including default values, the final and const keywords, and static types.

Control flow statements

Dart supports the usual control flow statements:

  1. if (year >= 2001) {
  2. print('21st century');
  3. } else if (year >= 1901) {
  4. print('20th century');
  5. }
  6.  
  7. for (var object in flybyObjects) {
  8. print(object);
  9. }
  10.  
  11. for (int month = 1; month <= 12; month++) {
  12. print(month);
  13. }
  14.  
  15. while (year < 2016) {
  16. year += 1;
  17. }

about control flow statements in Dart,including break and continue, switch and case, and assert.

Functions

We recommendspecifying the types of each function’s arguments and return value:

  1. int fibonacci(int n) {
  2. if (n == 0 || n == 1) return n;
  3. return fibonacci(n - 1) + fibonacci(n - 2);
  4. }
  5.  
  6. var result = fibonacci(20);

A shorthand => (arrow) syntax is handy for functions thatcontain a single 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().

about functions in Dart,including optional parameters, default parameter values, and lexical scope.

Dart comments usually start with //.

  1. // This is a normal, one-line comment.
  2.  
  3. /// This is a documentation comment, used to document libraries,
  4. /// doc comments specially.
  5.  
  6. /* Comments like these are also supported. */

Imports

To access APIs defined in other libraries, use import.

Read more about libraries and visibility in Dart,including library prefixes, 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’sdefined using a getter method (instead of a variable).

  1. class Spacecraft {
  2. String name;
  3. DateTime launchDate;
  4.  
  5. // Constructor, with syntactic sugar for assignment to members.
  6. Spacecraft(this.name, this.launchDate) {
  7. // Initialization code goes here.
  8. }
  9.  
  10. // Named constructor that forwards to the default one.
  11. Spacecraft.unlaunched(String name) : this(name, null);
  12.  
  13. int get launchYear =>
  14. launchDate?.year; // read-only non-final property
  15.  
  16. // Method.
  17. void describe() {
  18. print('Spacecraft: $name');
  19. if (launchDate != null) {
  20. int years =
  21. DateTime.now().difference(launchDate).inDays ~/
  22. 365;
  23. print('Launched: $launchYear ($years years ago)');
  24. } else {
  25. print('Unlaunched');
  26. }
  27. }
  28. }

You might use the Spacecraft class like this:

  1. var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
  2. voyager.describe();
  3.  
  4. var voyager3 = Spacecraft.unlaunched('Voyager III');
  5. voyager3.describe();

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 {
  2. num altitude;
  3. Orbiter(String name, DateTime launchDate, this.altitude)
  4. : super(name, launchDate);
  5. }

Read more about extending classes, the optional @override annotation, and more.

Mixins are a way of reusing code in multiple class hierarchies. The following class can act as a mixin:

  1. class Piloted {
  2. int astronauts = 1;
  3. void describeCrew() {
  4. print('Number of astronauts: $astronauts');
  5. }
  6. }

To add a mixin’s capabilities to a class, just extend the class with the mixin.

  1. class PilotedCraft extends Spacecraft with Piloted {
  2. // ···
  3. }

PilotedCraft now has the astronauts field as well as the describeCrew() method.

about mixins.

Interfaces and abstract classes

Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

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. void describe();
  2.  
  3. void describeWithEmphasis() {
  4. print('=========');
  5. describe();
  6. print('=========');
  7. }
  8. }

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 byusing and await.

  1. const oneSecond = Duration(seconds: 1);
  2. // ···
  3. Future<void> printWithDelay(String message) async {
  4. await Future.delayed(oneSecond);
  5. print(message);
  6. }

The method above is equivalent to:

  1. Future<void> printWithDelay(String message) {
  2. return Future.delayed(oneSecond).then((_) {
  3. print(message);
  4. });
  5. }

As the next example shows, async and await help make asynchronous codeeasy to read.

  1. Future<void> createDescriptions(Iterable<String> objects) async {
  2. for (var object in objects) {
  3. try {
  4. var file = File('$object.txt');
  5. if (await file.exists()) {
  6. var modified = await file.lastModified();
  7. print(
  8. 'File for $object already exists. It was modified on $modified.');
  9. continue;
  10. }
  11. await file.create();
  12. await file.writeAsString('Start describing $object in this file.');
  13. } on IOException catch (e) {
  14. print('Cannot create description for $object: $e');
  15. }
  16. }
  17. }

You can also use async, which gives you a nice, readable way to build streams.<!—?code-excerpt “misc/test/samples_test.dart (async)”?—>

  1. Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
  2. for (var object in objects) {
  3. await Future.delayed(oneSecond);
  4. yield '${craft.name} flies by $object';
  5. }
  6. }

aboutasynchrony support, including async functions, Future, Stream,and the asynchronous loop (await for).

Exceptions

To raise an exception, use throw:

To catch an exception, use a try statement with on or catch (or both):

  1. try {
  2. for (var object in flybyObjects) {
  3. var description = await File('$object.txt').readAsString();
  4. print(description);
  5. }
  6. } on IOException catch (e) {
  7. print('Could not describe object: $e');
  8. } finally {
  9. }

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, , and the difference betweenError and Exception.