MANNING Chris Buckett F OREWORD BY Seth Ladd www.it-ebooks.info Dart in Action www.it-ebooks.info www.it-ebooks.info Dart in Action CHRIS BUCKETT MANNING Shelter Island www.it-ebooks.info For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: orders@manning.com ©2013 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Development editor: Susanna Kline Manning Publications Co. Technical proofreader: John Evans 20 Baldwin Road Copyeditor: Tiffany Taylor PO Box 261 Proofreader: Toma Mulligan Shelter Island, NY 11964 Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617290862 Printed in the United States of America 12345678910–MAL –171615141312 www.it-ebooks.info v brief contents PART 1INTRODUCING DART 1 1 ■ Hello Dart 3 2 ■ “Hello World” with Dart tools 24 3 ■ Building and testing your own Dart app 40 PART 2CORE DART 69 4 ■ Functional first-class functions and closures 71 5 ■ Understanding libraries and privacy 94 6 ■ Constructing classes and interfaces 119 7 ■ Extending classes and interfaces 138 8 ■ Collections of richer classes 158 9 ■ Asynchronous programming with callbacks and futures 183 PART 3CLIENT-SIDE DART APPS 209 10 ■ Building a Dart web app 211 11 ■ Navigating offline data 237 12 ■ Communicating with other systems and languages 258 www.it-ebooks.info BRIEF CONTENTS vi PART 4SERVER-SIDE DART 281 13 ■ Server interaction with files and HTTP 283 14 ■ Sending, syncing, and storing data 308 15 ■ Concurrency with isolates 331 www.it-ebooks.info vii contents foreword xv preface xvii acknowledgments xix about this book xxi about the cover illustration xxv PART 1INTRODUCING DART 1 1 Hello Dart 3 1.1 What is Dart? 3 A familiar syntax to help language adoption 5 ■ Single-page application architecture 6 1.2 A look at the Dart language 7 String interpolation 7 ■ Optional types in action 9 Traditional class-based structure 10 ■ Implied interface definitions 11 ■ Factory constructors to provide default implementations 12 ■ Libraries and scope 13 ■ Functions as first-class objects 16 ■ Concurrency with isolates 17 1.3 Web programming with Dart 18 dart:html: a cleaner DOM library for the browser 18 ■ Dart and HTML5 19 www.it-ebooks.info CONTENTS viii 1.4 The Dart tool ecosystem 20 The Dart Editor 20 ■ Dart virtual machine 21 ■ Dartium 21 dart2js: the Dart-to-JavaScript converter 22 ■ Pub for package management 22 1.5 Summary 23 2 “Hello World” with Dart tools 24 2.1 The command-line Dart VM 25 2.2 “Hello World” with the Dart Editor 26 Exploring the Dart Editor tools 27 ■ The relationship between Dart and HTML files 30 ■ Running “Hello World” with Dartium 30 Using dart2js to convert to JavaScript 32 ■ Generating documentation with dartdoc 34 ■ Debugging Dart with breakpoints 34 2.3 Importing libraries to update the browser UI 35 Importing Dart libraries 36 ■ Accessing DOM elements with dart:html 37 ■ Dynamically adding new elements to the page 38 2.4 Summary 39 3 Building and testing your own Dart app 40 3.1 Building a UI with dart:html 41 Entry-point HTML 42 ■ Creating dart:html elements 42 Creating a new Element from HTML snippets 44 ■ Creating elements by tag name 45 ■ Adding elements to an HTML document 46 3.2 Building interactivity with browser events 49 Adding the PackList item from a button click 49 ■ Event handling with Dart’s flexible function syntax 50 ■ Responding to dart:html browser events 52 ■ Refactoring the event listener for reuse 53 Querying HTML elements in dart:html 54 3.3 Wrapping structure and functionality with classes 56 Dart classes are familiar 57 ■ Constructing the PackItem class 57 ■ Wrapping functionality with property getters and setters 59 3.4 Unit-testing the code 62 Creating unit tests 64 ■ Defining test expectations 64 Creating a custom matcher 66 3.5 Summary 67 www.it-ebooks.info CONTENTS ix PART 2CORE DART 69 4 Functional first-class functions and closures 71 4.1 Examining Dart functions 72 Function return types and the return keyword 74 ■ Providing input with function parameters 77 4.2 Using first-class functions 82 Local function declarations 83 ■ Defining strong function types 88 4.3 Closures 91 4.4 Summary 93 5 Understanding libraries and privacy 94 5.1 Defining and importing libraries in your code 95 Defining a library with the library keyword 96 ■ Importing libraries with import 98 5.2 Hiding functionality with library privacy 103 Using privacy in classes 105 ■ Using private functions in libraries 109 5.3 Organizing library source code 110 Using the part and part of keywords 111 5.4 Packaging your libraries 114 5.5 Scripts are runnable libraries 116 5.6 Summary 118 6 Constructing classes and interfaces 119 6.1 Defining a simple class 120 Coding against a class’s interface 121 ■ Formalizing interfaces with explicit interface definitions 123 ■ Using multiple interfaces 124 ■ Declaring property getters and setters 125 6.2 Constructing classes and interfaces 126 Constructing class instances 127 ■ Designing and using classes with multiple constructors 128 ■ Using factory constructors to create instances of abstract classes 129 ■ Reusing objects with factory constructors 130 ■ Using static methods and properties with factory constructors 132 www.it-ebooks.info [...]... string values, place them next to each other For example, var title = "Dart " "in " "Action" ; produces a single string variable containing "Dart in Action" The following listing shows the things you can do with strings using Dart s built -in print function, which outputs to standard output, server-side, or the browser debug console when run in a browser Listing 1.1 String interpolation in Dart void main()... ■ Testing future values 205 207 PART 3 CLIENT-SIDE DART APPS 209 10 Building a Dart web app 211 10.1 A single-page web app design Introducing DartExpense 212 Dart app execution flow 217 10.2 212 ■ Building a UI with dart: html Dart application structure 216 220 Understanding the Element interface 220 Element constructors in action 223 Building interaction with views and elements 225 Building a simple... print(o.toString()); print("$o"); r prefix outputs literal string without interpolation Multiline strings ignore first line break following """ Multiline strings can contain both single and double quotes String interpolation automatically calls toString() function } The output from this listing is Hello World $h $w Hello World HELLO WORLD The answer is 15 "Hello World" Instance... Persisting data offline with Web Storage 247 Converting Dart objects to JSON strings 248 Converting JSON strings to Dart objects 252 Storing data in browser web storage 253 ■ ■ 11.4 Summary 257 www.it-ebooks.info xii CONTENTS 12 Communicating with other systems and languages 258 12.1 Communicating with JavaScript 259 Sending data from Dart to JavaScript 262 Receiving data in JavaScript sent from Dart. .. www.manning.com/DartinAction Software requirements Working with Dart requires at the very least the Dart SDK, which is available from www.dartlang.org The Dart SDK is included in the Dart Editor download, which also includes the custom Dart browser, Dartium (essential for rapid Dart development), www.it-ebooks.info xxiv ABOUT THIS BOOK and the Dart to JavaScript converter This download is available for Windows,... Instance of 'Object' Instance of 'Object' You’ll use string interpolation and the print function a lot when experimenting with Dart, logging variables to help with debugging, and inserting values into HTML snippets www.it-ebooks.info 9 A look at the Dart language 1.2.2 Optional types in action One of the key differences between JavaScript and Dart is that Dart has the concept of types baked into the language... Server interaction with files and HTTP 283 13.1 Running server-side Dart scripts 284 Accessing command-line arguments 287 folders with dart: io 288 13.2 Serving browser HTTP requests Using the Dart HttpServer 13.3 295 ■ ■ Accessing files and 294 Serving static files over HTTP Serving clients with a RESTful API 297 299 Sending a directory list as JSON data 301 Sending the file content as JSON data 302 Adding... 6.3 Creating constant classes with final, unchanging variables 134 Final values and properties 134 The constructor initialization block 134 Using the const keyword to create a const constructor 135 ■ ■ 6.4 7 Summary 136 Extending classes and interfaces 138 7.1 Extending classes with inheritance 139 Class inheritance 140 Inheriting constructors 142 Overriding methods and properties 143 Including abstract... www.it-ebooks.info 4 CHAPTER 1 Hello Dart in the Dart virtual machine, allowing both the client and the server parts of your apps to be coded in the same language The language syntax is very similar to Java, C#, and JavaScript One of the primary goals for Dart was that the language seem familiar This is a tiny Dart script, comprising a single function called main: Single entry-point function main() executes... Lottery 192 Ensuring that all async callbacks are complete before continuing 193 Nesting callbacks to enforce async execution order 195 ■ ■ 9.3 Introducing the Future and Completer pair 197 Passing around future values 198 Ordering async calls by chaining futures 199 Waiting for all futures to complete 200 Transforming nonfuture values into futures 202 ■ ■ 9.4 Unit-testing async APIs 203 Testing async callback . MANNING Chris Buckett F OREWORD BY Seth Ladd www.it-ebooks.info Dart in Action www.it-ebooks.info www.it-ebooks.info Dart in Action CHRIS. classes and interfaces 119 6.1 Defining a simple class 120 Coding against a class’s interface 121 ■ Formalizing interfaces with explicit interface definitions