Preface

You don’t need to be an expert web developer to build web apps. With Dart, you can be productive as you build high-performance apps for the modern web.

Our aim for this book is to be a useful introduction to the Dart language, libraries, and tools. Because this book is short and Dart is young, you might also need to refer to the Dart website at http://dartlang.org—both for details and for updates. For the latest news, keep an eye on the Dart page on Google+.

Another important website is this book’s GitHub project. The text for this work is available there under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License. Source code files for this book’s samples are also there, in the code/ subdirectory. Downloading the sample code from GitHub is much easier than copying it from the book.

If you find an error in the sample code or text, please create an issue.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This icon signifies a tip or suggestion.

Note

This icon signifies a general note.

Caution

This icon indicates a warning or caution.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/oreillymedia/dart_up_and_running.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significiant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Dart: Up and Running by Kathy Walrath and Seth Ladd (O’Reilly). Copyright 2014 Kathy Walrath and Seth Ladd, 978-1-449-33089-7.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online (www.safaribooksonline.com) is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/Dart_Up_and_Running.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Content Updates

This section gives details about how the book has changed between each of its three printings.

Changes in the Third Printing: February 19, 2014

We’ve changed the text and examples to reflect these language changes:

  • Instance variables can no longer be const. Use static const variables instead.

  • The ? operator for testing whether an optional parameter has been set is no longer in the language.

  • Keys in map literals no longer need to be strings.

  • Dart now has Symbols and symbol literals (#identifier): Symbols.

  • Function equality testing is easier: Testing Functions for Equality.

  • Bitwise operators have higher precedence than they used to.

We’ve also updated the content to reflect API changes. In dart:core:

  • Set’s isSubsetOf() method is gone. Instead, use the Set containsAll() method. You can convert any Iterable to a Set using toSet().

  • The Collection class is gone, so we’ve changed the way we talked about sets, lists, and maps in Collections, and we talk more about Iterable.

  • The functionality in the former dart:uri library is now in the Uri class in dart:core. The top-level functions encodeUri(), encodeUriComponent(), decodeUri(), and decodeUriComponent() are now static methods in Uri named (respectively) encodeFull(), encodeComponent(), decodeFull(), and decodeComponent(). To create a Uri from a string, you now use the static parse() method. Uri now has a single constructor, which takes the arguments that the Uri.fromComponents() constructor used to take. Finally, the domain field is now named host.

  • The @deprecated, @override, and @proxy annotations moved from the meta package to dart:core.

In dart:io:

  • File’s openWrite() method now has no required parameters but two optional named parameters. The mode parameter has a default value of FileMode.WRITE.

  • File’s readAsString() and readAsLines() methods no longer require a parameter. Instead, they have an optional named parameter (encoding), with a default value of Encoding.UTF_8.

  • IOSink’s methods for writing data have changed. To write string data, instead of addString() use write(). The method for writing binary data was temporarily renamed to writeBytes(), but reverted back to add().

A new dart:convert library replaces dart:json and dart:uri:

  • Instead of a StringDecoder, use UTF8.decoder to convert UTF-8 characters into a Dart string.

  • Instead of a LineTransformer, use a LineSplitter object to split a stream of strings into a stream of individual lines.

  • Where you used to use dart:json’s top-level parse() and stringify() functions, use JSON.decode() and JSON.encode(), respectively.

  • Where you used to use dart:uri’s top-level decodeUri() and encodeUri() functions, use UTF8.decode() and UTF8.encode(), respectively.

Other API changes include:

  • In dart:html, the query() and queryAll() methods changed to querySelector() and querySelectorAll(), respectively.

  • The dart:crypto library moved out of the SDK (to http://pub.dartlang.org/packages/crypto).

  • The AsyncError class was removed (from dart:async).

  • The dart:isolate library was refactored to have only core primitives. We removed its coverage from the book but expect higher level APIs to come along that make using isolates easier.

  • The main() function now takes an optional argument (List<String>).

The sections that talk about tools have changed, too:

  • The dart_analyzer tool has been replaced by dartanalyzer.

  • Command-line arguments for many tools have changed.

  • The pub tool now has build and serve commands, which work with transformers to convert your source files into their final format.

  • We fleshed out the dart2js docs.

  • We removed the dartdoc coverage from the book, since we expect the interface to change significantly.

We also added new coverage of previously undocumented features and tweaked existing coverage. In the language tour:

  • Added Adding Features to a Class: Mixins.

  • In Keywords, marked which keywords are built-in identifiers and discussed how they differ from reserved words.

  • Added coverage of the + operator for strings.

  • Discussed using expressions (such as function calls) as arguments to a non-default constructor.

  • Added examples of using the @override and @proxy annotations.

  • Changed the doc comment example to match the latest guidelines, and pointed to Guidelines for Dart Doc Comments.

In the library tour:

  • Added dart:mirrors—Reflection.

  • Added examples of parsing non-decimal numbers.

  • Removed the incorrect new from the example of using Future.wait().

  • Removed coverage of Completer, which is no longer recommended.

  • Added Stream.

Throughout the book, we updated links to related topics.

Finally, we completely rewrote Chapter 5 to feature a new example (Dartiverse Search).

Changes in the Second Printing: March 29, 2013

We’ve updated the content to reflect the following changes since the first printing:

  • Using part of in additional library files is now required, not optional.

  • In M2, several APIs changed:

    • In the dart:html library, the elements property of Element changed to children.

    • Names in dart:html changed to conform to Dart naming standards. In particular, innerHTML became innerHtml.

    • The charCodes() method of String became a getter, so we removed the parentheses from all references to charCodes.

    • The readAsText() method of File became readAsString().

    • Constructors for the Date class changed.

    • NullPointerException no longer exists.

    • RegExp no longer has a const constructor.

    • The return type of StringBuffer’s add() method changed to void. Code that used to chain calls to add() should now use method cascades instead.

  • The recommended way for web apps to use dart.js is now to have a local copy, preferably one downloaded using the browser pub package.

  • Metadata support was added to the language. See Metadata.

  • We added references to the Web UI package, which provides a higher level, scalable approach to creating UIs for web apps.

  • In M3, mixins were added to the language, enabling code re-use between classes.

  • The core libraries were greatly revised in M3 or shortly afterward. Changes include:

    • Some methods changed to fields or getters. This meant we had to remove the () after hashCode, isEmpty, and isNan. We also changed getKeys() to keys, and getValues() to values.

    • The Iterable class was beefed up, affecting all Collections such as Lists and Sets. The former Collection methods filter() and map() moved to Iterable, and the name of filter() changed to where(). (map() was briefly renamed to mappedBy(), but due to public feedback that decision was reversed.) The some() method changed to any(). Many values returned by Iterables are now lazily-filled Iterables; you can use toList() or toSet() to force evaluation. We recommend extending Iterable rather than just implementing it, so you can take advantage of added functionality. More details are in the article Iterables.

    • The Iterator interface changed from next() and hasNext() to current and moveNext().

    • The dart:json library no longer has a JSON class. Former JSON static methods such as parse() and stringify() are now top-level functions.

    • Date is now named DateTime, and the fromString() constructor is now a static method named parse().

    • Event-handler registration used to be .on.event.add(); now it’s .onEvent.listen.

    • The dart:html HttpRequest get() method was replaced by getString() and request(), which return Future<String> and Future<HttpRequest>, respectively.

    • The dart:html Window setTimeout() method is gone; instead, use Future.delayed() or, if you know what you’re doing, a Timer.

    • Timer and Completer moved from dart:isolate to a new library called dart:async. The Timer constructors now take a Duration instead of an int.

    • The Future chain() and handleException() methods are gone, replaced by then() and catchError().

    • The String splitChars() method is gone; instead, use split() with an empty string argument. String’s charCodes getter and charCodeAt() method are gone; to get UTF-16 code units, use String’s codeUnits or codeUnitAt() instead.

    • The StringBuffer add() and addAll() methods were replaced by write() and writeAll(), respectively.

    • The dart:io library changed significantly after M3, as did all I/O in Dart. I/O now centers around the dart:async library’s Stream and Future classes, instead of callbacks. The InputStream and OutputStream classes were replaced with classes implementing Stream and IOSink. A new FileSystemEntity class is the superclass of File and Directory. To create a new HttpServer, you now use the static bind() method. For more information, see the announcement.

    • The most used dart:crypto methods for hashes changed from update() and digest() to add() and close().

We corrected or clarified some text, such as:

  • Bitwise operators are implemented in int, not num.

  • The is and as examples (in Type Test Operators) aren’t completely equivalent.

We also added sections for some pre-existing features:

Finally, Figure 1-1 now uses a more recent benchmark and has the latest numbers.

Acknowledgments

We’d like to thank the many people who contributed to this book. We hope we haven’t forgotten anyone, but we probably have.

The following Dart engineers and managers gave us prompt, helpful reviews and information for the sections corresponding to their areas of responsibility: Mads Ager, Peter von der Ahé, Justin Fagnani, Emily Fortuna, Søren Gjesse, Dan Grove, Matthias Hausner, Florian Loitsch, Ryan Macnak, Sam McCall, John McCutchan, Vijay Menon, John Messerly, Anton Muhin, Lasse R.H. Nielsen, Bob Nystrom, Keerti Parthasarathy, Ivan Posva, Konstantin Scheglov, Brian Wilkerson, and Jaime Wren.

We’d especially like to thank the people who reviewed even bigger swaths of the book or contributed in other, large ways:

  • JJ Behrens, whose careful look at the first draft of the book helped us catch errors and inconsistencies, as well as rework Chapter 5 to be more interesting, and less of a laundry list. He also created a system for testing our samples.

  • Shailen Tuli, who helped test our examples although he didn’t even work for Google.

  • Mary Campione, whose stream-of-consciousness review of the entire book, performed while she was first learning the language, helped us find and fix many confusing spots, as well as some errors. Later she reviewed and updated our samples, and she implemented continuous build testing for our samples on drone.io.

  • Phil Quitslund, who did a big-picture review of the book and gave us guidance and encouragement.

  • Kasper Lund, whose review caught issues that only someone with his expert, comprehensive knowledge of the Dart language and libraries could have found.

  • Gilad Bracha, the language spec writer whose reviews of the language chapter were invaluable for getting language details right. We couldn’t cover everything, so we look forward to his future work on making all the corners of the language understandable to all Dart programmers.

  • Anders Johnsen, who wrote the Dartiverse Search app and reviewed Chapter 5’s walkthrough of that app.

Other Googlers helped, as well. Vivian Cromwell, the head of Chrome Developer Relations, supported our work on this book. Andres Ferrate, the Google Press liaison to O’Reilly, helped simplify the process of getting the book published. Myisha Harris gave us excellent legal advice.

The people at O’Reilly were extremely helpful. Meghan Blanchette, our editor, kept everything going smoothly, monitoring our progress in the nicest possible way. Christopher Hearse, Marisa LaFleur, and Melanie Yarbrough checked our work and helped us make some last-minute fixes that improved the final result. We’d also like to thank the good people who manage the author workflow and make working on an O’Reilly book such a pleasure. We personally worked with Sarah Schneider, Jessica Hosman, and Rachel James.

Finally, we thank Lars Bak and Kasper Lund for writing the foreword, and most of all for creating Dart.

Get Dart: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.