Language samples

This collection is not exhaustive—it’s just a brief introduction to the language for people who like to learn by example. You might also want to check out the language and library tours, or the Dart cheatsheet codelab.

Language tour

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.

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() {
  2. print('Hello, World!');
  3. }

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. for (var object in flybyObjects) {
  7. print(object);
  8. }
  9. for (int month = 1; month <= 12; month++) {
  10. print(month);
  11. }
  12. while (year < 2016) {
  13. year += 1;
  14. }

Read more about control flow statements in Dart, including 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) {
  2. if (n == 0 || n == 1) return n;
  3. return fibonacci(n - 1) + fibonacci(n - 2);
  4. }
  5. var result = fibonacci(20);

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

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.
  2. /// This is a documentation comment, used to document libraries,
  3. /// classes, and their members. Tools like IDEs and dartdoc treat
  4. /// doc comments specially.
  5. /* Comments like these are also supported. */

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
  2. import 'dart:math';
  3. // Importing libraries from external packages
  4. import 'package:test/test.dart';
  5. // Importing files
  6. import 'path/to/my_other_file.dart';

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

You might use the Spacecraft class like this:

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

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 {
  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

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.

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 {
  2. // ···
  3. }

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 {
  2. void describe();
  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 by using async 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 code easy 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.

  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. }

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) {
  2. throw StateError('No astronauts.');
  3. }

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. flybyObjects.clear();
  10. }

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.