- A tour of the core libraries
- dart:core - numbers, collections, strings, and more
- dart:async - asynchronous programming
- dart:math - math and random
- dart:convert - decoding and encoding JSON, UTF-8, and more
- dart:html - browser-based apps
A tour of the core libraries
This page shows you how to use the major features in Dart’s core libraries.It’s just an overview, and by no means comprehensive.Whenever you need more details about a class,consult the Dart API reference.
- dart:core
- Built-in types, collections, and other core functionality.This library is automatically imported into every Dart program.
- dart:async
- Support for asynchronous programming, with classes such as Future and Stream.
- dart:math
- Mathematical constants and functions, plus a random number generator.
- dart:convert
- Encoders and decoders for converting between different data representations, including JSON and UTF-8.
- dart:html
- DOM and other APIs for browser-based apps.
- dart:io
- I/O for programs that can use the Dart VM,including Flutter apps, servers, and command-line scripts.
This page is just an overview;it covers only a few dart:* librariesand no third-party libraries.
Other places to find library information are thepub.dev site and theDart web developer library guide.You can find API documentation for all dart:* libraries in theDart API reference or, if you’re using Flutter,the Flutter API reference.
DartPad tip: You can play with the code in this page by copying it into a DartPad.
dart:core - numbers, collections, strings, and more
The dart:core library (API reference)provides a small but critical set of built-in functionality.This library is automatically imported into every Dart program.
Printing to the console
The top-level print() method takes a single argument (any Object)and displays that object’s string value (as returned by toString())in the console.
1. print(anObject);
2. print('I drink $tea.');
For more information on basic strings and toString(), seeStrings in the language tour.
Numbers
The dart:core library defines the num, int, and double classes, whichhave some basic utilities for working with numbers.
You can convert a string into an integer or double with the parse()methods of int and double, respectively:
1. assert(int.parse('42') == 42);
2. assert(int.parse('0x42') == 66);
3. assert(double.parse('0.50') == 0.5);
Or use the parse() method of num, which creates an integer if possibleand otherwise a double:
1. assert(num.parse('42') is int);
2. assert(num.parse('0x42') is int);
3. assert(num.parse('0.50') is double);
To specify the base of an integer, add a radix parameter:
1. assert(int.parse('42', radix: 16) == 66);
Use the toString() method to convert anint or double to a string. To specify the number of digits to the rightof the decimal, use toStringAsFixed(). To specify thenumber of significant digits in the string, usetoStringAsPrecision():
1. // Convert an int to a string.
2. assert(42.toString() == '42');
4. // Convert a double to a string.
5. assert(123.456.toString() == '123.456');
7. // Specify the number of digits after the decimal.
8. assert(123.456.toStringAsFixed(2) == '123.46');
10. // Specify the number of significant figures.
11. assert(123.456.toStringAsPrecision(2) == '1.2e+2');
12. assert(double.parse('1.2e+2') == 120.0);
For more information, see the API documentation forint,double, and num. Also seethe dart:math section.
Strings and regular expressions
A string in Dart is an immutable sequence of UTF-16 code units.The language tour has more information aboutstrings.You can use regular expressions (RegExp objects)to search within strings and toreplace parts of strings.
The String class defines such methods as split(), contains(),startsWith(), endsWith(), and more.
Searching inside a string
You can find particular locations within a string, as well as checkwhether a string begins with or ends with a particular pattern. Forexample:
1. // Check whether a string contains another string.
2. assert('Never odd or even'.contains('odd'));
4. // Does a string start with another string?
5. assert('Never odd or even'.startsWith('Never'));
7. // Does a string end with another string?
8. assert('Never odd or even'.endsWith('even'));
10. // Find the location of a string inside a string.
11. assert('Never odd or even'.indexOf('odd') == 6);
Extracting data from a string
You can get the individual characters from a string as Strings or ints,respectively. To be precise, you actually get individual UTF-16 codeunits; high-numbered characters such as the treble clef symbol(‘\u{1D11E}’) are two code units apiece.
You can also extract a substring or split a string into a list ofsubstrings:
1. // Grab a substring.
2. assert('Never odd or even'.substring(6, 9) == 'odd');
4. // Split a string using a string pattern.
5. var parts = 'structured web apps'.split(' ');
6. assert(parts.length == 3);
7. assert(parts[0] == 'structured');
9. // Get a UTF-16 code unit (as a string) by index.
10. assert('Never odd or even'[0] == 'N');
12. // Use split() with an empty string parameter to get
13. // a list of all characters (as Strings); good for
14. // iterating.
15. for (var char in 'hello'.split('')) {
16. print(char);
17. }
19. // Get all the UTF-16 code units in the string.
20. var codeUnitList =
21. 'Never odd or even'.codeUnits.toList();
22. assert(codeUnitList[0] == 78);
Converting to uppercase or lowercase
You can easily convert strings to their uppercase and lowercasevariants:
1. // Convert to uppercase.
2. assert('structured web apps'.toUpperCase() ==
3. 'STRUCTURED WEB APPS');
5. // Convert to lowercase.
6. assert('STRUCTURED WEB APPS'.toLowerCase() ==
7. 'structured web apps');
Note: These methods don’t work for every language. For example, the Turkish alphabet’s dotless I is converted incorrectly.
Trimming and empty strings
Remove all leading and trailing white space with trim(). To checkwhether a string is empty (length is zero), use isEmpty.
1. // Trim a string.
2. assert(' hello '.trim() == 'hello');
4. // Check whether a string is empty.
5. assert(''.isEmpty);
7. // Strings with only white space are not empty.
8. assert(' '.isNotEmpty);
Replacing part of a string
Strings are immutable objects, which means you can create them but youcan’t change them. If you look closely at the String API reference,you’ll notice thatnone of the methods actually changes the state of a String. For example,the method replaceAll() returns a new String without changing theoriginal String:
1. var greetingTemplate = 'Hello, NAME!';
2. var greeting =
3. greetingTemplate.replaceAll(RegExp('NAME'), 'Bob');
5. // greetingTemplate didn't change.
6. assert(greeting != greetingTemplate);
Building a string
To programmatically generate a string, you can use StringBuffer. AStringBuffer doesn’t generate a new String object until toString() iscalled. The writeAll() method has an optional second parameter thatlets you specify a separator—in this case, a space.
1. var sb = StringBuffer();
2. sb
3. ..write('Use a StringBuffer for ')
4. ..writeAll(['efficient', 'string', 'creation'], ' ')
5. ..write('.');
7. var fullString = sb.toString();
9. assert(fullString ==
10. 'Use a StringBuffer for efficient string creation.');
Regular expressions
The RegExp class provides the same capabilities as JavaScript regularexpressions. Use regular expressions for efficient searching and patternmatching of strings.
1. // Here's a regular expression for one or more digits.
2. var numbers = RegExp(r'\d+');
4. var allCharacters = 'llamas live fifteen to twenty years';
5. var someDigits = 'llamas live 15 to 20 years';
7. // contains() can use a regular expression.
8. assert(!allCharacters.contains(numbers));
9. assert(someDigits.contains(numbers));
11. // Replace every match with another string.
12. var exedOut = someDigits.replaceAll(numbers, 'XX');
13. assert(exedOut == 'llamas live XX to XX years');
You can work directly with the RegExp class, too. The Match classprovides access to a regular expression match.
1. var numbers = RegExp(r'\d+');
2. var someDigits = 'llamas live 15 to 20 years';
4. // Check whether the reg exp has a match in a string.
5. assert(numbers.hasMatch(someDigits));
7. // Loop through all matches.
8. for (var match in numbers.allMatches(someDigits)) {
9. print(match.group(0)); // 15, then 20
10. }
More information
Refer to the String API reference for a full list ofmethods. Also see the API reference for StringBuffer,Pattern,RegExp, and Match.
Collections
Dart ships with a core collections API, which includes classes forlists, sets, and maps.
Lists
As the language tour shows, you can use literals to create andinitialize lists. Alternatively, use one of the Listconstructors. The List class also defines several methods for addingitems to and removing items from lists.
1. // Use a List constructor.
2. var vegetables = List();
4. // Or simply use a list literal.
5. var fruits = ['apples', 'oranges'];
7. // Add to a list.
8. fruits.add('kiwis');
10. // Add multiple items to a list.
11. fruits.addAll(['grapes', 'bananas']);
13. // Get the list length.
14. assert(fruits.length == 5);
16. // Remove a single item.
17. var appleIndex = fruits.indexOf('apples');
18. fruits.removeAt(appleIndex);
19. assert(fruits.length == 4);
21. // Remove all elements from a list.
22. fruits.clear();
23. assert(fruits.isEmpty);
Use indexOf() to find the index of an object in a list:
1. var fruits = ['apples', 'oranges'];
3. // Access a list item by index.
4. assert(fruits[0] == 'apples');
6. // Find an item in a list.
7. assert(fruits.indexOf('apples') == 0);
Sort a list using the sort() method. You can provide a sortingfunction that compares two objects. This sorting function must return <0 for smaller, 0 for the same, and > 0 for bigger. The followingexample uses compareTo(), which is defined byComparable and implemented by String.
1. var fruits = ['bananas', 'apples', 'oranges'];
3. // Sort a list.
4. fruits.sort((a, b) => a.compareTo(b));
5. assert(fruits[0] == 'apples');
Lists are parameterized types, so you can specify the type that a listshould contain:
1. // This list should contain only strings.
2. var fruits = List<String>();
4. fruits.add('apples');
5. var fruit = fruits[0];
6. assert(fruit is String);
1. fruits.add(5); // Error: 'int' can't be assigned to 'String'
Refer to the List API reference for a full list of methods.
Sets
A set in Dart is an unordered collection of unique items. Because a setis unordered, you can’t get a set’s items by index (position).
1. var ingredients = Set();
2. ingredients.addAll(['gold', 'titanium', 'xenon']);
3. assert(ingredients.length == 3);
5. // Adding a duplicate item has no effect.
6. ingredients.add('gold');
7. assert(ingredients.length == 3);
9. // Remove an item from a set.
10. ingredients.remove('gold');
11. assert(ingredients.length == 2);
Use contains() and containsAll() to check whether one or moreobjects are in a set:
1. var ingredients = Set();
2. ingredients.addAll(['gold', 'titanium', 'xenon']);
4. // Check whether an item is in the set.
5. assert(ingredients.contains('titanium'));
7. // Check whether all the items are in the set.
8. assert(ingredients.containsAll(['titanium', 'xenon']));
An intersection is a set whose items are in two other sets.
1. var ingredients = Set();
2. ingredients.addAll(['gold', 'titanium', 'xenon']);
4. // Create the intersection of two sets.
5. var nobleGases = Set.from(['xenon', 'argon']);
6. var intersection = ingredients.intersection(nobleGases);
7. assert(intersection.length == 1);
8. assert(intersection.contains('xenon'));
Refer to the Set API reference for a full list of methods.
Maps
A map, commonly known as a dictionary or hash, is an unorderedcollection of key-value pairs. Maps associate a key to some value foreasy retrieval. Unlike in JavaScript, Dart objects are not maps.
You can declare a map using a terse literal syntax, or you can use atraditional constructor:
1. // Maps often use strings as keys.
2. var hawaiianBeaches = {
3. 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
4. 'Big Island': ['Wailea Bay', 'Pololu Beach'],
5. 'Kauai': ['Hanalei', 'Poipu']
6. };
8. // Maps can be built from a constructor.
9. var searchTerms = Map();
11. // Maps are parameterized types; you can specify what
12. // types the key and value should be.
13. var nobleGases = Map<int, String>();
You add, get, and set map items using the bracket syntax. Use remove()to remove a key and its value from a map.
1. var nobleGases = {54: 'xenon'};
3. // Retrieve a value with a key.
4. assert(nobleGases[54] == 'xenon');
6. // Check whether a map contains a key.
7. assert(nobleGases.containsKey(54));
9. // Remove a key and its value.
10. nobleGases.remove(54);
11. assert(!nobleGases.containsKey(54));
You can retrieve all the values or all the keys from a map:
1. var hawaiianBeaches = {
2. 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
3. 'Big Island': ['Wailea Bay', 'Pololu Beach'],
4. 'Kauai': ['Hanalei', 'Poipu']
5. };
7. // Get all the keys as an unordered collection
8. // (an Iterable).
9. var keys = hawaiianBeaches.keys;
11. assert(keys.length == 3);
12. assert(Set.from(keys).contains('Oahu'));
14. // Get all the values as an unordered collection
15. // (an Iterable of Lists).
16. var values = hawaiianBeaches.values;
17. assert(values.length == 3);
18. assert(values.any((v) => v.contains('Waikiki')));
To check whether a map contains a key, use containsKey(). Because mapvalues can be null, you cannot rely on simply getting the value for thekey and checking for null to determine the existence of a key.
1. var hawaiianBeaches = {
2. 'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
3. 'Big Island': ['Wailea Bay', 'Pololu Beach'],
4. 'Kauai': ['Hanalei', 'Poipu']
5. };
7. assert(hawaiianBeaches.containsKey('Oahu'));
8. assert(!hawaiianBeaches.containsKey('Florida'));
Use the putIfAbsent() method when you want to assign a value to a keyif and only if the key does not already exist in a map. You must providea function that returns the value.
1. var teamAssignments = {};
2. teamAssignments.putIfAbsent(
3. 'Catcher', () => pickToughestKid());
4. assert(teamAssignments['Catcher'] != null);
Refer to the Map API reference for a full list of methods.
Common collection methods
List, Set, and Map share common functionality found in many collections.Some of this common functionality is defined by the Iterable class,which List and Set implement.
Note: Although Map doesn’t implement Iterable, you can get Iterables from it using the Map keys and values properties.
Use isEmpty or isNotEmpty to check whether a list, set, or map has items:
1. var coffees = [];
2. var teas = ['green', 'black', 'chamomile', 'earl grey'];
3. assert(coffees.isEmpty);
4. assert(teas.isNotEmpty);
To apply a function to each item in a list, set, or map, you can useforEach():
1. var teas = ['green', 'black', 'chamomile', 'earl grey'];
3. teas.forEach((tea) => print('I drink $tea'));
When you invoke forEach() on a map, your function must take twoarguments (the key and value):
1. hawaiianBeaches.forEach((k, v) {
2. print('I want to visit $k and swim at $v');
3. // I want to visit Oahu and swim at
4. // [Waikiki, Kailua, Waimanalo], etc.
5. });
Iterables provide the map() method, which gives you all the results ina single object:
1. var teas = ['green', 'black', 'chamomile', 'earl grey'];
3. var loudTeas = teas.map((tea) => tea.toUpperCase());
4. loudTeas.forEach(print);
Note: The object returned by map() is an Iterable that’s lazily evaluated: your function isn’t called until you ask for an item from the returned object.
To force your function to be called immediately on each item, usemap().toList() or map().toSet():
1. var loudTeas =
2. teas.map((tea) => tea.toUpperCase()).toList();
Use Iterable’s where() method to get all the items that match acondition. Use Iterable’s any() and every() methods to check whethersome or all items match a condition.
1. var teas = ['green', 'black', 'chamomile', 'earl grey'];
3. // Chamomile is not caffeinated.
4. bool isDecaffeinated(String teaName) =>
5. teaName == 'chamomile';
7. // Use where() to find only the items that return true
8. // from the provided function.
9. var decaffeinatedTeas =
10. teas.where((tea) => isDecaffeinated(tea));
11. // or teas.where(isDecaffeinated)
13. // Use any() to check whether at least one item in the
14. // collection satisfies a condition.
15. assert(teas.any(isDecaffeinated));
17. // Use every() to check whether all the items in a
18. // collection satisfy a condition.
19. assert(!teas.every(isDecaffeinated));
For a full list of methods, refer to the Iterable API reference,as well as those for List,Set, and Map.
URIs
The Uri class providesfunctions to encode and decode strings for use in URIs (which you mightknow as URLs). These functions handle characters that are special forURIs, such as & and =. The Uri class also parses and exposes thecomponents of a URI—host, port, scheme, and so on.
Encoding and decoding fully qualified URIs
To encode and decode characters except those with special meaning in aURI (such as /, :, &, #), use the encodeFull() anddecodeFull() methods. These methods are good for encoding or decodinga fully qualified URI, leaving intact special URI characters.
1. var uri = 'https://example.org/api?foo=some message';
3. var encoded = Uri.encodeFull(uri);
4. assert(encoded ==
5. 'https://example.org/api?foo=some%20message');
7. var decoded = Uri.decodeFull(encoded);
8. assert(uri == decoded);
Notice how only the space between some and message was encoded.
Encoding and decoding URI components
To encode and decode all of a string’s characters that have specialmeaning in a URI, including (but not limited to) /, &, and :, usethe encodeComponent() and decodeComponent() methods.
1. var uri = 'https://example.org/api?foo=some message';
3. var encoded = Uri.encodeComponent(uri);
4. assert(encoded ==
5. 'https%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message');
7. var decoded = Uri.decodeComponent(encoded);
8. assert(uri == decoded);
Notice how every special character is encoded. For example, / isencoded to %2F.
Parsing URIs
If you have a Uri object or a URI string, you can get its parts usingUri fields such as path. To create a Uri from a string, use theparse() static method:
1. var uri =
2. Uri.parse('https://example.org:8080/foo/bar#frag');
4. assert(uri.scheme == 'https');
5. assert(uri.host == 'example.org');
6. assert(uri.path == '/foo/bar');
7. assert(uri.fragment == 'frag');
8. assert(uri.origin == 'https://example.org:8080');
See the Uri API reference for more URI components that you can get.
Building URIs
You can build up a URI from individual parts using the Uri()constructor:
1. var uri = Uri(
2. scheme: 'https',
3. host: 'example.org',
4. path: '/foo/bar',
5. fragment: 'frag');
6. assert(
7. uri.toString() == 'https://example.org/foo/bar#frag');
Dates and times
A DateTime object is a point in time. The time zone is either UTC or thelocal time zone.
You can create DateTime objects using several constructors:
1. // Get the current date and time.
2. var now = DateTime.now();
4. // Create a new DateTime with the local time zone.
5. var y2k = DateTime(2000); // January 1, 2000
7. // Specify the month and day.
8. y2k = DateTime(2000, 1, 2); // January 2, 2000
10. // Specify the date as a UTC time.
11. y2k = DateTime.utc(2000); // 1/1/2000, UTC
13. // Specify a date and time in ms since the Unix epoch.
14. y2k = DateTime.fromMillisecondsSinceEpoch(946684800000,
15. isUtc: true);
17. // Parse an ISO 8601 date.
18. y2k = DateTime.parse('2000-01-01T00:00:00Z');
The millisecondsSinceEpoch property of a date returns the number ofmilliseconds since the “Unix epoch”—January 1, 1970, UTC:
1. // 1/1/2000, UTC
2. var y2k = DateTime.utc(2000);
3. assert(y2k.millisecondsSinceEpoch == 946684800000);
5. // 1/1/1970, UTC
6. var unixEpoch = DateTime.utc(1970);
7. assert(unixEpoch.millisecondsSinceEpoch == 0);
Use the Duration class to calculate the difference between two dates andto shift a date forward or backward:
1. var y2k = DateTime.utc(2000);
3. // Add one year.
4. var y2001 = y2k.add(Duration(days: 366));
5. assert(y2001.year == 2001);
7. // Subtract 30 days.
8. var december2000 = y2001.subtract(Duration(days: 30));
9. assert(december2000.year == 2000);
10. assert(december2000.month == 12);
12. // Calculate the difference between two dates.
13. // Returns a Duration object.
14. var duration = y2001.difference(y2k);
15. assert(duration.inDays == 366); // y2k was a leap year.
Warning: Using a Duration to shift a DateTime by days can be problematic, due to clock shifts (to daylight saving time, for example). Use UTC dates if you must shift days.
For a full list of methods,refer to the API reference for DateTime and Duration.
Utility classes
The core library contains various utility classes, useful for sorting,mapping values, and iterating.
Comparing objects
Implement the Comparableinterface to indicate that an object can be compared to another object,usually for sorting. The compareTo() method returns < 0 forsmaller, 0 for the same, and > 0 for bigger.
1. class Line implements Comparable<Line> {
2. final int length;
3. const Line(this.length);
5. @override
6. int compareTo(Line other) => length - other.length;
7. }
9. void main() {
10. var short = const Line(1);
11. var long = const Line(100);
12. assert(short.compareTo(long) < 0);
13. }
Implementing map keys
Each object in Dart automatically provides an integer hash code, andthus can be used as a key in a map. However, you can override thehashCode getter to generate a custom hash code. If you do, you mightalso want to override the == operator. Objects that are equal (via==) must have identical hash codes. A hash code doesn’t have to beunique, but it should be well distributed.
1. class Person {
2. final String firstName, lastName;
4. Person(this.firstName, this.lastName);
6. // Override hashCode using strategy from Effective Java,
7. // Chapter 11.
8. @override
9. int get hashCode {
10. int result = 17;
11. result = 37 * result + firstName.hashCode;
12. result = 37 * result + lastName.hashCode;
13. return result;
14. }
16. // You should generally implement operator == if you
17. // override hashCode.
18. @override
19. bool operator ==(dynamic other) {
20. if (other is! Person) return false;
21. Person person = other;
22. return (person.firstName == firstName &&
23. person.lastName == lastName);
24. }
25. }
27. void main() {
28. var p1 = Person('Bob', 'Smith');
29. var p2 = Person('Bob', 'Smith');
30. var p3 = 'not a person';
31. assert(p1.hashCode == p2.hashCode);
32. assert(p1 == p2);
33. assert(p1 != p3);
34. }
Iteration
The Iterable and Iterator classessupport for-in loops. Extend (if possible) or implement Iterablewhenever you create a class that can provide Iterators for use in for-inloops. Implement Iterator to define the actual iteration ability.
1. class Process {
2. // Represents a process...
3. }
5. class ProcessIterator implements Iterator<Process> {
6. @override
7. Process get current => ...
8. @override
9. bool moveNext() => ...
10. }
12. // A mythical class that lets you iterate through all
13. // processes. Extends a subclass of [Iterable].
14. class Processes extends IterableBase<Process> {
15. @override
16. final Iterator<Process> iterator = ProcessIterator();
17. }
19. void main() {
20. // Iterable objects can be used with for-in.
21. for (var process in Processes()) {
22. // Do something with the process.
23. }
24. }
Exceptions
The Dart core library defines many common exceptions and errors.Exceptions are considered conditions that you can plan ahead for andcatch. Errors are conditions that you don’t expect or plan for.
A couple of the most common errors are:
- NoSuchMethodError
- Thrown when a receiving object (which might be null) does notimplement a method.
- ArgumentError
- Can be thrown by a method that encounters an unexpected argument.
Throwing an application-specific exception is a common way to indicatethat an error has occurred. You can define a custom exception byimplementing the Exception interface:
1. class FooException implements Exception {
2. final String msg;
4. const FooException([this.msg]);
6. @override
7. String toString() => msg ?? 'FooException';
8. }
For more information, seeExceptions(in the language tour) and the Exception API reference.
dart:async - asynchronous programming
Asynchronous programming often uses callback functions, but Dartprovides alternatives: Future and Stream objects. AFuture is like a promise for a result to be provided sometime in thefuture. A Stream is a way to get a sequence of values, such as events.Future, Stream, and more are in thedart:async library (API reference).
Note: You don’t always need to use the Future or Stream APIs directly. The Dart language supports asynchronous coding using keywords such as async and await. See the asynchronous programming codelab for details.
The dart:async library works in both web apps and command-line apps. Touse it, import dart:async:
1. import 'dart:async';
Version note: As of Dart 2.1, you don’t need to import dart:async to use the Future and Stream APIs, because dart:core exports those classes.
Future
Future objects appear throughout the Dart libraries, often as the objectreturned by an asynchronous method. When a future completes, its valueis ready to use.
Using await
Before you directly use the Future API, consider using await instead.Code that uses await expressions can be easier to understandthan code that uses the Future API.
Consider the following function. It uses Future’s then() methodto execute three asynchronous functions in a row,waiting for each one to complete before executing the next one.
1. runUsingFuture() {
2. // ...
3. findEntryPoint().then((entryPoint) {
4. return runExecutable(entryPoint, args);
5. }).then(flushThenExit);
6. }
The equivalent code with await expressionslooks more like synchronous code:
1. runUsingAsyncAwait() async {
2. // ...
3. var entryPoint = await findEntryPoint();
4. var exitCode = await runExecutable(entryPoint, args);
5. await flushThenExit(exitCode);
6. }
An async function can catch exceptions from Futures.For example:
1. var entryPoint = await findEntryPoint();
2. try {
3. var exitCode = await runExecutable(entryPoint, args);
4. await flushThenExit(exitCode);
5. } catch (e) {
6. // Handle the error...
7. }
Important: Async functions return Futures. If you don’t want your function to return a future, then use a different solution. For example, you might call an async function from your function.
For more information on using await and related Dart language features,see the asynchronous programming codelab.
Basic usage
You can use then() to schedule code that runs when the future completes. Forexample, HttpRequest.getString() returns a Future, since HTTP requestscan take a while. Using then() lets you run some code when that Futurehas completed and the promised string value is available:
1. HttpRequest.getString(url).then((String result) {
2. print(result);
3. });
Use catchError() to handle any errors or exceptions that a Futureobject might throw.
1. HttpRequest.getString(url).then((String result) {
2. print(result);
3. }).catchError((e) {
4. // Handle or ignore the error.
5. });
The then().catchError() pattern is the asynchronous version oftry-catch.
Important: Be sure to invoke catchError() on the result of then()—not on the result of the original Future. Otherwise, the catchError() can handle errors only from the original Future’s computation, but not from the handler registered by then().
Chaining multiple asynchronous methods
The then() method returns a Future, providing a useful way to runmultiple asynchronous functions in a certain order. If the callbackregistered with then() returns a Future, then() returns anequivalent Future. If the callback returns a value of any other type,then() creates a new Future that completes with the value.
1. Future result = costlyQuery(url);
2. result
3. .then((value) => expensiveWork(value))
4. .then((_) => lengthyComputation())
5. .then((_) => print('Done!'))
6. .catchError((exception) {
7. /* Handle exception... */
8. });
In the preceding example, the methods run in the following order:
costlyQuery()expensiveWork()lengthyComputation()Here is the same code written using await:
1. try {
2. final value = await costlyQuery(url);
3. await expensiveWork(value);
4. await lengthyComputation();
5. print('Done!');
6. } catch (e) {
7. /* Handle exception... */
8. }
Waiting for multiple futures
Sometimes your algorithm needs to invoke many asynchronous functions andwait for them all to complete before continuing. Use the Future.wait()static method to manage multiple Futures and wait for them to complete:
1. Future deleteLotsOfFiles() async => ...
2. Future copyLotsOfFiles() async => ...
3. Future checksumLotsOfOtherFiles() async => ...
5. await Future.wait([
6. deleteLotsOfFiles(),
7. copyLotsOfFiles(),
8. checksumLotsOfOtherFiles(),
9. ]);
10. print('Done with all the long steps!');
Stream
Stream objects appear throughout Dart APIs, representing sequences ofdata. For example, HTML events such as button clicks are delivered usingstreams. You can also read a file as a stream.
Using an asynchronous for loop
Sometimes you can use an asynchronous for loop (await for)instead of using the Stream API.
Consider the following function.It uses Stream’s listen() methodto subscribe to a list of files,passing in a function literal that searches each file or directory.
1. void main(List<String> arguments) {
2. // ...
3. FileSystemEntity.isDirectory(searchPath).then((isDir) {
4. if (isDir) {
5. final startingDir = Directory(searchPath);
6. startingDir
7. .list(
8. recursive: argResults[recursive],
9. followLinks: argResults[followLinks])
10. .listen((entity) {
11. if (entity is File) {
12. searchFile(entity, searchTerms);
13. }
14. });
15. } else {
16. searchFile(File(searchPath), searchTerms);
17. }
18. });
19. }
The equivalent code with await expressions,including an asynchronous for loop (await for),looks more like synchronous code:
1. Future main(List<String> arguments) async {
2. // ...
3. if (await FileSystemEntity.isDirectory(searchPath)) {
4. final startingDir = Directory(searchPath);
5. await for (var entity in startingDir.list(
6. recursive: argResults[recursive],
7. followLinks: argResults[followLinks])) {
8. if (entity is File) {
9. searchFile(entity, searchTerms);
10. }
11. }
12. } else {
13. searchFile(File(searchPath), searchTerms);
14. }
15. }
Important: Before using await for, make sure that it makes the code clearer and that you really do want to wait for all of the stream’s results. For example, you usually should not use await for for DOM event listeners, because the DOM sends endless streams of events. If you use await for to register two DOM event listeners in a row, then the second kind of event is never handled.
For more information on using await and relatedDart language features, see theasynchronous programming codelab.
Listening for stream data
To get each value as it arrives, either use await for orsubscribe to the stream using the listen() method:
1. // Find a button by ID and add an event handler.
2. querySelector('#submitInfo').onClick.listen((e) {
3. // When the button is clicked, it runs this code.
4. submitData();
5. });
In this example, the onClick property is a Stream object provided bythe “submitInfo” button.
If you care about only one event, you can get it using a property suchas first, last, or single. To test the event before handling it,use a method such as firstWhere(), lastWhere(), or singleWhere().
If you care about a subset of events, you can use methods such asskip(), skipWhile(), take(), takeWhile(), and where().
Transforming stream data
Often, you need to change the format of a stream’s data before you canuse it. Use the transform() method to produce a stream with adifferent type of data:
1. var lines = inputStream
2. .transform(utf8.decoder)
3. .transform(LineSplitter());
This example uses two transformers. First it uses utf8.decoder totransform the stream of integers into a stream of strings. Then it usesa LineSplitter to transform the stream of strings into a stream ofseparate lines. These transformers are from the dart:convert library (see thedart:convert section).
Handling errors and completion
How you specify error and completion handling codedepends on whether you use an asynchronous for loop (await for)or the Stream API.
If you use an asynchronous for loop,then use try-catch to handle errors.Code that executes after the stream is closedgoes after the asynchronous for loop.
1. Future readFileAwaitFor() async {
2. var config = File('config.txt');
3. Stream<List<int>> inputStream = config.openRead();
5. var lines = inputStream
6. .transform(utf8.decoder)
7. .transform(LineSplitter());
8. try {
9. await for (var line in lines) {
10. print('Got ${line.length} characters from stream');
11. }
12. print('file is now closed');
13. } catch (e) {
14. print(e);
15. }
16. }
If you use the Stream API,then handle errors by registering an onError listener.Run code after the stream is closed by registeringan onDone listener.
1. var config = File('config.txt');
2. Stream<List<int>> inputStream = config.openRead();
4. inputStream
5. .transform(utf8.decoder)
6. .transform(LineSplitter())
7. .listen((String line) {
8. print('Got ${line.length} characters from stream');
9. }, onDone: () {
10. print('file is now closed');
11. }, onError: (e) {
12. print(e);
13. });
More information
For some examples of using Future and Stream in command-line apps,see the dart:io tour.Also see these articles, codelabs, and tutorials:
- Asynchronous programming: futures, async, await
- Futures and error handling
- Asynchronous programming: streams
- Creating streams in Dart
- Dart asynchronous programming: Isolates and event loops
dart:math - math and random
The dart:math library (API reference)provides common functionality such as sine and cosine,maximum and minimum, and constants such as pi and e. Most of thefunctionality in the Math library is implemented as top-level functions.
To use this library in your app, import dart:math.
1. import 'dart:math';
Trigonometry
The Math library provides basic trigonometric functions:
1. // Cosine
2. assert(cos(pi) == -1.0);
4. // Sine
5. var degrees = 30;
6. var radians = degrees * (pi / 180);
7. // radians is now 0.52359.
8. var sinOf30degrees = sin(radians);
9. // sin 30° = 0.5
10. assert((sinOf30degrees - 0.5).abs() < 0.01);
Note: These functions use radians, not degrees!
Maximum and minimum
The Math library provides max() and min() methods:
1. assert(max(1, 1000) == 1000);
2. assert(min(1, -1000) == -1000);
Math constants
Find your favorite constants—pi, e, and more—in the Math library:
1. // See the Math library for additional constants.
2. print(e); // 2.718281828459045
3. print(pi); // 3.141592653589793
4. print(sqrt2); // 1.4142135623730951
Random numbers
Generate random numbers with the Random class. You canoptionally provide a seed to the Random constructor.
1. var random = Random();
2. random.nextDouble(); // Between 0.0 and 1.0: [0, 1)
3. random.nextInt(10); // Between 0 and 9.
You can even generate random booleans:
1. var random = Random();
2. random.nextBool(); // true or false
More information
Refer to the Math API reference for a full list of methods.Also see the API reference for num,int, and double.
dart:convert - decoding and encoding JSON, UTF-8, and more
The dart:convert library (API reference)has converters for JSON and UTF-8, as well as support for creatingadditional converters. JSON is a simple text format for representingstructured objects and collections. UTF-8 is a common variable-widthencoding that can represent every character in the Unicode characterset.
The dart:convert library works in both web apps and command-line apps.To use it, import dart:convert.
1. import 'dart:convert';
Decoding and encoding JSON
Decode a JSON-encoded string into a Dart object with jsonDecode():
1. // NOTE: Be sure to use double quotes ("),
2. // not single quotes ('), inside the JSON string.
3. // This string is JSON, not Dart.
4. var jsonString = '''
5. [
6. {"score": 40},
7. {"score": 80}
8. ]
9. ''';
11. var scores = jsonDecode(jsonString);
12. assert(scores is List);
14. var firstScore = scores[0];
15. assert(firstScore is Map);
16. assert(firstScore['score'] == 40);
Encode a supported Dart object into a JSON-formatted string withjsonEncode():
1. var scores = [
2. {'score': 40},
3. {'score': 80},
4. {'score': 100, 'overtime': true, 'special_guest': null}
5. ];
7. var jsonText = jsonEncode(scores);
8. assert(jsonText ==
9. '[{"score":40},{"score":80},'
10. '{"score":100,"overtime":true,'
11. '"special_guest":null}]');
Only objects of type int, double, String, bool, null, List, or Map (withstring keys) are directly encodable into JSON. List and Map objects areencoded recursively.
You have two options for encoding objects that aren’t directlyencodable. The first is to invoke encode() with a second argument: afunction that returns an object that is directly encodable. Your secondoption is to omit the second argument, in which case the encoder callsthe object’s toJson() method.
For more examples and links to JSON-related packages, seeUsing JSON.
Decoding and encoding UTF-8 characters
Use utf8.decode() to decode UTF8-encoded bytes to a Dart string:
1. List<int> utf8Bytes = [
2. 0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
3. 0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
4. 0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
5. 0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
6. 0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1
7. ];
9. var funnyWord = utf8.decode(utf8Bytes);
11. assert(funnyWord == 'Îñţérñåţîöñåļîžåţîờñ');
To convert a stream of UTF-8 characters into a Dart string, specifyutf8.decoder to the Stream transform() method:
1. var lines =
2. utf8.decoder.bind(inputStream).transform(LineSplitter());
3. try {
4. await for (var line in lines) {
5. print('Got ${line.length} characters from stream');
6. }
7. print('file is now closed');
8. } catch (e) {
9. print(e);
10. }
Use utf8.encode() to encode a Dart string as a list of UTF8-encodedbytes:
1. List<int> encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
3. assert(encoded.length == utf8Bytes.length);
4. for (int i = 0; i < encoded.length; i++) {
5. assert(encoded[i] == utf8Bytes[i]);
6. }
Other functionality
The dart:convert library also has converters for ASCII and ISO-8859-1(Latin1). For details, see the API reference for the dart:convert library.
dart:html - browser-based apps
Use the dart:html library to program the browser, manipulate objects andelements in the DOM, and access HTML5 APIs. DOM stands for Document ObjectModel, which describes the hierarchy of an HTML page.
Other common uses of dart:html are manipulating styles (CSS), gettingdata using HTTP requests, and exchanging data usingWebSockets.HTML5 (and dart:html) has manyadditional APIs that this section doesn’t cover. Only web apps can usedart:html, not command-line apps.
Note: For a higher level approach to web app UIs, use a web framework such as AngularDart.
To use the HTML library in your web app, import dart:html:
1. import 'dart:html';
Manipulating the DOM
To use the DOM, you need to know about windows, documents,elements, and nodes.
A Window object representsthe actual window of the web browser. Each Window has a Document object,which points to the document that’s currently loaded.
(本文超出站点单文档体积上限,已截断)
