đź”™ Quay lại trang tải sách pdf ebook Dart in Action Ebooks NhĂłm Zalo Chris Buckett FOREWORD BY Seth Ladd MANNING Dart in Action Dart in Action CHRIS BUCKETT MANNING Shelter Island 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: [email protected] ©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 1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12 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 v vi BRIEF CONTENTS 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 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 vii viii CONTENTS 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 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 x CONTENTS 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 Summary 136 7 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 classes in a class hierarchy 144 7.2 Everything is an object 147 Testing the “is-an” relationship with Object 147 â–  Using the “is an” Object relationship 149 â–  Using toString() functionality inherited from the base Object class 150 â–  Intercepting noSuchMethod() calls 151 â–  Other default functionality of the Object class 153 7.3 Introducing the dynamic type 154 Using the dynamic type annotation 156 7.4 Summary 156 8 Collections of richer classes 158 8.1 Working with collections of data 159 Collections of objects 160 â–  Using the concrete implementations of the Collection interface 164 â–  Making collections specific with generics 166 â–  Storing lists of key/value pairs with generic maps 170 8.2 Building your own generic classes 173 Defining a generic class 173 â–  Using your custom generic class 175 â–  Restricting the types that can be used as placeholders 175 8.3 Operator overloading 176 Overloading comparison operators 177 â–  Surprising use for operator overloading 179 â–  Overloading indexer operators 179 8.4 Summary 182 9 Asynchronous programming with callbacks and futures 183 9.1 Why web apps should be asynchronous 185 Modifying your app to be asynchronous 187 CONTENTS xi 9.2 Using callbacks with async programming 190 Adding async callbacks to Dart 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 functions 205 â–  Testing future values 205 9.5 Summary 207 PART 3CLIENT-SIDE DART APPS ....................................209 10 Building a Dart web app 211 10.1 A single-page web app design 212 Introducing DartExpense 212 â–  Dart application structure 216 Dart app execution flow 217 10.2 Building a UI with dart:html 220 Understanding the Element interface 220 â–  Element constructors in action 223 â–  Building interaction with views and elements 225 â–  Building a simple generic grid 228 10.3 Handling browser events with dart:html 231 Managing browser event flow 232 â–  Common event types 235 10.4 Summary 236 11 Navigating offline data 237 11.1 Integrating navigation with the browser 239 Using pushState() to add items to the browser history 239 Listening for popState events 241 11.2 Using browser cookies to enhance user experience 243 Storing data in a cookie 244 â–  Reading data from a cookie 245 11.3 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 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 263 â–  Sending data from JavaScript to Dart 265 12.2 Communicating with external servers 268 Understanding the same-origin security restrictions 269 Using JSONP to request data from external servers 270 12.3 Building installable, server-less browser apps 273 Using AppCache to run applications offline 273 â–  Packaging your app as a Chrome web app 277 12.4 Summary 280 PART 4SERVER-SIDE DART ...........................................281 13 Server interaction with files and HTTP 283 13.1 Running server-side Dart scripts 284 Accessing command-line arguments 287 â–  Accessing files and folders with dart:io 288 13.2 Serving browser HTTP requests 294 Using the Dart HttpServer 295 â–  Serving static files over HTTP 297 13.3 Serving clients with a RESTful API 299 Sending a directory list as JSON data 301 â–  Sending the file content as JSON data 302 â–  Adding the client-side user interface 303 13.4 Summary 307 14 Sending, syncing, and storing data 308 14.1 Serving DartExpense from the server 309 14.2 Using web sockets for two-way communication 310 Connecting web sockets on the client side 311 â–  Handling web socket connections on the server 312 â–  Using web sockets for cross browser synchronization 315 14.3 Storing data with HttpClient and CouchDB 320 A quick CouchDB primer 321 â–  Sharing the Expense model class between client and server 324 â–  Adding server support for data persistence 324 14.4 Summary 329 CONTENTS xiii 15 Concurrency with isolates 331 15.1 Using isolates as units of work 332 Creating an isolate 332 â–  One-way isolate communication 335 Two-way isolate communication 338 15.2 Loading code dynamically 341 Spawning an isolate from a filename 343 â–  Defining a dynamic source file 344 15.3 Spawning multiple workers 345 15.4 Summary 350 appendix A Core language reference 351 appendix B Defining classes and libraries 371 index 386 foreword When I heard that we were starting work on Dart, a structured and scalable language with a fast virtual machine, a powerful editor, and a compiler to JavaScript, at first I didn’t believe it. “Could this be the project to make web programming easier for developers like me?” I hopefully wondered. Coming from a structured language back ground, and used to powerful developer tools, I’d been waiting for a more productive way to build larger modern web apps. The Dart project sounded like just what I was looking for. I grew up on object-oriented languages like C++, Java, and Ruby as I first built interactive websites and then later rich client-side web apps. I learned to be pro ductive with classes, objects, and modular code. I appreciated IDEs for their analysis, refactoring, and navigation capabilities because they helped me write more complex, larger applications. Life was great. Looking for a new opportunity, I was lucky enough to get a job working with the Chrome team. For the first time, I learned how to exploit the modern browser, and I dove into the many HTML5 features. The modern web evolves very quickly and reaches so many people that it’s an exciting place to be. Life was even better. Although I loved the iterative and fast-paced nature of web development, I was missing my structured languages and helpful tools. I wanted a way to build for modern browsers with IDEs that could perform code completion, languages that had real classes, and more. So when I heard about Dart, I jumped at the opportunity to help out. Build for the most exciting platform with a development experience that I’m familiar and produc tive with? You bet! xv xvi FOREWORD I wasn’t the only developer who immediately joined the fun. The author of this book, Chris Buckett, is one of our earliest adopters of Dart. He started the Dartwatch blog on the day that Google announced Dart, and it’s still going strong. Chris has been with the project since the beginning, so it’s only natural that he is one of the first to write a book to help other developers learn Dart. Chris is some sort of super author, for he has been able to write this book as the project was going through numerous changes to its libraries and language. He’s done a great job covering the many different aspects and features of the Dart project. I especially enjoyed his numerous examples of not only the core language features, but also the more advanced HTML5 features. Chris embraces the single-page app and shows how to use Dart to build modern browser-based apps. You’ll even learn how to program server-side Dart with this book! After a year of hard work, tens of thousands of commits, thousands of bugs, and great community feedback, the dream of structured web programming is a reality. Although Dart isn’t done yet, thanks to Chris’s book, together we can have fun build ing great apps for the modern web. Enjoy! SETH LADD DEVELOPER ADVOCATE GOOGLE preface In October 2011, rumor became reality when Google released a new language aimed at developing complex, Google-scale web applications. An internal Google email titled “Future of JavaScript” had appeared on the web a month earlier, indicating that a lan guage, possibly to be known as Dash, was undergoing development within Google, with the aim of being a better language for the web than JavaScript. Born out of frustration with the slow progress in evolving JavaScript, partly caused by the numerous interested parties and committees, this new language aimed to be everything JavaScript could be if it were invented now. Its key goal was to “maintain the dynamic nature of JavaScript, but have a better performance profile and be amenable to tooling for large projects.” It would also be able to cross-compile to JavaScript. This language was released as a tech nical preview to the wider world and given the name Dart. I had just come out the back of a major GWT project at my employer, creating a bespoke document-referencing application designed for touch screens that would be deployed in non-computer-friendly environments. Google Web Toolkit (GWT) is a technology that Google created for cross-compiling Java to JavaScript. GWT lets devel opers benefit from the structure, type-safety, and tooling provided by Java, while still being able to target browsers natively without requiring plug-ins such as Flash or Sil verlight. Having spent the last two years writing GWT code and coordinating develop ers across three countries, I knew the value of being able to use tooling to validate code at integration points—something that was lacking when trying to achieve the same with JavaScript. The ability to reuse code on both the client and the server also appealed to me—I had seen the benefit. xvii xviii PREFACE Keen to know more about this new Dart language, I read all the documentation that was available. At the time, this consisted of the source code, some sample proj ects, and the language specification. It seemed that if I were to make the effort of get ting the knowledge into my head, it would be worth sharing with the wider community through blog posts. I started the Dartwatch blog and shared a series of simple descriptions of how to achieve common tasks in Dart, such as how to organize a project, how to create classes, and how to interact with the browser. One thing led to another, and I was approached by Manning about the possibility of writing a book on Dart. Just over a year later, the result is in print. Over the last year, Dart has had time to mature, and its developers have been lis tening and responding to feedback. Dart’s Milestone 1 release is imminent, and there have been many changes to the original language specification as a result of real world use by the language’s early adopters. A community of these early adopters has also been creating tools and libraries such as database drivers, 2D and 3D graphics libraries, and MVC frameworks, many of which can be found on GitHub or on the Dartwatch website. Dart Milestone 1 is a major achievement and gives Dart developers the chance to build on the core Dart language to create a great set of libraries and APIs to turn Dart into the “batteries included” language that the team at Google envisages. Every day, Dart improves; and thanks to its open source nature, you can watch (and even contrib ute to) the commits by many developers into the Dart source code repository. I hope that this book helps you build great Dart apps. acknowledgments It turns out that writing a book isn’t as straightforward as I first thought, and without the guidance and effort of the all who were involved at Manning, it’s unlikely you would be reading this book today. Thanks to Michael Stephens for setting me on this path in the first place; it’s been a fun project. Many people behind the scenes at Man ning have contributed by proofreading, editing, preparing images, and performing the myriad other tasks that go into producing a book such as this—thank you all. A special mention must also go to two people at Manning. First, thanks to Bert Bates, whose mentoring in the early days showed me how to turn what could other wise have been a dry reference manual into something that is more pleasing to read. In the back of my mind when writing each chapter was the mantra, “Tell Bert why he should care about this subject…” Second, thanks to my editor, Susanna Kline, who kept each chapter focused and helped keep me motivated and on schedule for the best part of a year. Dart has a vibrant developer community centered around the dartlang mailing list and Google+. From that community, John Evans and Kevin Moore deserve thanks for their technical proofreading of the subject matter, along with Adam Singer, Matthew Butler, and Ladislav Thon, whose contributions are always welcome. Also from the developer community, thanks to all those readers who provided valu able feedback by reviewing the book at its various stages of development: AndrĂ© Roberge, Carl Taswell, Chad Davis, Craig Lancaster, Dylan Scott, Glenn Stokol, Jon Skeet, Olivier Nouguier, Rick Goff, Rodney Bollinger, Rokesh Jankie, Steve Pretty, Terry Birch, and Willhelm Lehman. xix xx ACKNOWLEDGMENTS Thanks also to all the contributors to the book’s bulletin board, who helped spot the inevitable typos, and to the readers of Manning’s Early Access Program (MEAP). Finally, thanks to all those on the Dart team, including Seth Ladd, who helped me and many other early adopters keep up to date with the various changes as Dart evolved from its initial release to the language you see today. Special thanks to Seth for kindly contributing the foreword to the book. about this book This book will help you learn the Dart language, understand the Dart ecosystem, and write Dart code targeted to run in modern web browsers and on the server. You’ll use the latest HTML5 technologies to build apps capable of running disconnected in the browser and create Dart servers capable of two-way communication with browsers. As a structured language, Dart is ideal for building large-scale apps in distributed teams. And with tools to enable automatic checking and validation of your and your fellow developers’ code, Dart helps make your life as a developer easier. Audience This book is aimed at developers who have been frustrated by the lack of structure and tooling available to them when building browser-based apps. If you have a work ing knowledge of Java, C#, or JavaScript, then you’ll be able to dive right in and get working with Dart. Whether you prefer to build interactive user interfaces or are happier creating effi cient back-end code, you’ll find that Dart, combined with modern browser technol ogy, brings the structure of the server to the front end, and the flexibility, dynamism, and speed of browser development to the back end. Whether you’re a novice web developer or are experienced with writing structured code, this book will help you get up to speed with Dart language concepts. The book uses an example-based format, with examples throughout each chapter to introduce new concepts. The text indicates Dart’s similarities to other languages such as Java and JavaScript, as well as shows its differences. xxi xxii ABOUT THIS BOOK Like Java, Dart has great tools; and like JavaScript, Dart doesn’t require a compile step, which means that with this book you can quickly get ready to start building client and server Dart applications. Roadmap This book is structured to get you working with Dart as quickly as possible. It’s split into four parts. Part 1 includes overview chapters designed to get you up and running with Dart: â–  Chapter 1 provides an overview of the language features and concepts and why Dart exists. If you’ve ever been exasperated by the lack of typing and documen tation that could be encoded in a browser-based language, this chapter will help you to understand the philosophy behind Dart. This base will give you an idea of the types of large-scale web apps you can build with Dart. â–  Chapter 2 discusses the wider Dart ecosystem, including the rich tooling you get by choosing a structured web-development language created by a market-leading web company. With the technical resources to concentrate on a whole-developer experience, rather than just the language, Google has created an IDE, a custom Dart browser for rapid development, a server-side virtual machine, and other tools to help you build quality code. â–  In chapter 3, you’ll build an example web app, getting a taste of how Dart inter acts with the browser. You’ll build a user interface, listen for browser events, and create unit tests to confirm the validity of your code. Part 2 covers the core language features: â–  Chapter 4 examines functions, which are first-class objects in Dart. JavaScript developers will be familiar with some of the techniques of functional program ming, but Java and C# developers will find many new ideas that are common practice in browser-based web development. â–  Chapter 5 moves on to building the structure of your app by using Dart’s library system, and shows how that relates to privacy. Dart’s privacy mechanism might surprise Java and C# developers and will be a welcome treat to those experi enced with JavaScript. â–  Chapters 6, 7, and 8 explore Dart’s class and interface structure. Classes form the backbone of any reasonable-size app, and knowing how to effectively build class hierarchies and use library classes provided by other developers is an essential skill. â–  Chapter 9 returns to functional programming to explore the asynchronous nature of web APIs. You’ll learn how to work with future values, that is, variables that will have a value at some point in the future. This will leave you ready to start working with the APIs provided by Dart’s client and server libraries. ABOUT THIS BOOK xxiii Part 3 discusses building client-side browser apps: â–  In chapter 10, you’ll learn about Dart’s event loop and create a user-interface in Dart. â–  Chapter 11 builds on the structure of your app to add browser-based navigation, persistent client-side storage, and interaction with the JSON data format. â–  By chapter 12, you’ll be ready to start connecting your app to external systems, such as external JavaScript and third-party server APIs. Although Dart is tar geted at all modern web browsers, in this chapter you’ll also learn how to pack age your app for deployment as a Chrome app in Google’s Web Store. When you reach part 4, you’ll be ready to hook up your app with the server side: â–  Chapter 13 introduces building a command-line Dart application, accessing the filesystem, and serving HTTP data to build a simple file server. â–  Chapter 14 builds on client-side communication by connecting the client side to a server-side database and performing two-way communication with Web Sockets technology to push data to the client. â–  In chapter 15, knowing how to interact with the server, you’ll be ready to learn how Dart achieves concurrency through its system of isolates, a message-passing threading model that provides a safer means of concurrency than the equiva lent in Java or C#. You’ll also use the isolate system to load Dart code dynami cally into your running application. This gives you a great basis for building plug-ins and extensions into your app. The appendixes provide a concise reference to and examples of the core Dart lan guage, giving you a quick guide to Dart’s specific syntax idiosyncrasies and quirks. Code conventions and downloads All the source code in the text uses a fixed width font like this. The text contains many code snippets and diagrams, and there are complete, annotated code listings to show key concepts. These code listings, snippets, and diagrams usually relate to the surrounding body text and are a key part of learning Dart. In some cases, code has been reformatted to fit the page, but in general, the code has been written to take page width into account. Although the examples are often simple in order to to show a key concept or example, the body text and code annota tions provide additional depth. Source code for the examples in this book is avaiable for download from the pub lisher’s website at 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), xxiv ABOUT THIS BOOK and the Dart to JavaScript converter. This download is available for Windows, Mac, and Linux. Author Online Your purchase of Dart in Action includes free access to a private web forum run by Man ning Publications, where you can make comments about the book, ask technical ques tions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser at www.manning.com/DartinAction. This page explains how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum. Manning’s commitment to its readers is to provide a venue where a meaningful dialogue among individual readers, and between readers and the author, can take place. It’s not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions, lest his interest stray! The Author Online forum and archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. About the author Chris Buckett is a technical consultant responsible for delivering enterprise-scale, web-based business applications. Chris runs the popular Dartwatch.com blog and is an active contributor to the dartlang mailing list. about the cover illustration The figure on the cover of Dart in Action is captioned an “Island Woman from Zadar, Dalmatia.” The illustration is taken from the reproduction published in 2006 of a 19th-century collection of costumes and ethnographic descriptions entitled Dalmatia by Professor Frane Carrara (1812 - 1854), an archaelogist and historian and the first director of the Musuem of Antiquity in Split, Croatia. The illustrations were obtained from a helpful librarian at the Ethnographic Museum (formerly the Museum of Antiquity), itself situated in the Roman core of the medieval center of Split: the ruins of Emperor Diocletian’s retirement palace from around AD 304. The book includes finely colored illustrations of figures from different regions of Croatia, accompanied by descriptions of the costumes and of everyday life. Zadar is an historic town located on the Adriatic coast of Croatia; its orgins date to the Stone Age. Zadar faces the islands of Uglian and Pasman, from which it is sepa rated by the narrow Zadar Strait. The promontory on which the old city stands used to be separated from the mainland by a deep moat which has since become landfilled. The region is rich in influences of the many nation states that ruled it through the centuries, from the Greeks and Romans to the Venetians and Austrians. Today, the city is part of the Republic of Croatia. Dress codes have changed since the 19th century and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns or regions. Perhaps we have traded cultural diver sity for a more varied personal life—certainly for a more varied and fast-paced techno logical life. xxv xxvi ABOUT THE COVER ILLUSTRATION At a time when it is hard to tell one computer book from another, Manning cele brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Carrara’s pictures. Part 1 Introducing Dart Dart is a great language for developing web apps. In chapter 1, you’ll get an overview of why Dart was created and how Dart solves some of the problems experienced by many developers coming to web development. You’ll discover some of the features the language offers and see why single-page web applica tions are a good architecture for building apps in Dart. In chapter 2, you’ll start to come to grips with the rich tool ecosystem that comes with Dart. Dart is more than a language—it’s an entire development tool set, including an IDE, a custom developer browser for testing and debugging, and a Dart to JavaScript converter. In chapter 3, you’ll build a simple Dart app, learning how to create a browser based, single-page web app. Through this example application, you’ll be intro duced to the language, including Dart’s classes, functions, and variables. By the end of the chapter, you’ll have a Dart project with a functioning user interface and accompanying unit tests, and you’ll be ready to start learning about the core Dart language in Part 2. This chapter covers â–  Basics of the Dart development platform â–  A look at the Dart language â–  Tools for building Dart applications Hello Dart Dart is an exciting language that raises the possibility of building complex web applications more quickly and accurately than ever before. In this chapter, you’ll find out how the Dart language and its tool ecosystem fit together, you’ll discover some of the key features of the Dart language, and you’ll see how you can you use Dart to begin building single-page web applications. 1.1 What is Dart? Dart is an open source, structured programming language for creating complex, browser-based web applications. You can run applications created in Dart either by using a browser that directly supports Dart code or by compiling your Dart code to JavaScript. Dart has a familiar syntax, and it’s class-based, optionally typed, and single threaded. It has a concurrency model called isolates that allows parallel execution, which we discuss in chapter 15. In addition to running Dart code in web browsers and converting it to JavaScript, you can also run Dart code on the command line, hosted 3 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, compris ing a single function called main: Single entry-point function main() executes when script is fully loaded main() { var d = "Dart"; String w = "World"; print("Hello ${d} ${w}"); } Optional typing (no type specified) Type annotation (String type specified) Uses string interpolation to output "Hello Dart World" to browser console or stdout This script can be embedded in an HTML page’s Entry-point function must be called main() //do something }(); Entry-point function can be called anything main() function is called automatically when the browser has fully loaded Entry-point function must be explicitly called to start it running Figure 2.2 The Dart Editor is a lightweight version of the Eclipse tool. 2.2.1 Exploring the Dart Editor tools The Dart Editor provides the standard range of developer tools such as method and property autocomplete, refactoring, code navigation, and syntax checking and debugging. When you edit your app with the Dart Editor, your code, and the code of all the external libraries that make up your application, is validated for errors and warnings. Internally, the Dart Editor uses the dart_analyzer tool to provide static analysis of the Dart code. This tool can also be used on the command line—for exam ple, to integrate it into a continuous-build system such as Hudson, CruiseControl, or Bamboo. NOTE At the time of writing, the command-line version of the dart_analyzer tool is available only on Mac and Linux platforms. The Windows version is still under development. You can use the output from dart_analyzer in the Dart Editor to highlight lines of code that that may contain errors or could be considered warnings, as shown in figure 2.3. This error-checking also allows the Dart Editor to provide some quick-fix capabilities. For example, the Editor gives you the option to create a new prnt(String string) func tion stub based on its knowledge of the missing prnt() method. The warning shown in figure 2.3 is telling you that a + method is missing on the String object. This may be valid code, as you’ll see when we look at handling noSuchMethod() in chapter 7, so it’s flagged as a warning rather than an error. You can execute code that contains warnings; you can’t execute code that contains errors. When you run the “Hello World” script, its output is redirected to the Dart Editor’s own console instead of running in a separate console window. The Dart Editor is using the same Dart VM binary that you used in the previous section when you ran the 28 CHAPTER 2 “Hello World” with Dart tools Trying to concatenate two strings with a + operator produces a warning. This code will be allowed to run but may cause a runtime exception. A straightforward typo, trying to call a prnt() function instead of a print() function, is highlighted as an error. Figure 2.3 Errors and warnings are shown in the Dart Editor. “Hello World” script from the command line. Figure 2.4 shows the output in the Edi tor’s console window. The Dart Editor contains a number of tools to help you navigate around code: your own code and any external libraries you’re using, whether brought in from the Dart SDK or open source libraries. CODE NAVIGATION AND THE STANDARD LIBRARIES The Dart project is open source. That philosophy is baked into the language, and as such, all the standard library code is open source, too. Thus, using the Editor’s code navigation features, if you want to see what the dart:html ButtonElement class looks like or examine the dart:core List code structure and comments, they’re right there at your fingertips in plain text. You can navigate directly from your code to the declaration site by using the Open Declaration (F3) command. This command works for both your own code and any other libraries you import. It’s useful, for example, to be able to navigate a hierarchy of method calls throughout several libraries to discover the underlying reason for a particular bug or way of working—especially when you’re developing in a team and The output from the Dart VM is shown in the Dart Editor’s console screen. Figure 2.4 The Dart VM produces output in the Editor console. “Hello World” with the Dart Editor 29 The Outline view shows the structure of a source file. The Callers view shows who is calling a specific function or method. In this instance, it shows that function foo() is called by function main(), on line 3. Figure 2.5 The Dart Editor Callers and Outline views someone else has implemented an underlying library or you’re using third-party libraries from the web. The Dart Editor also has useful Outline and Callers views. The Outline view lets you visualize the outline of your source file, showing top-level functions, classes, and class members. The Callers view, which you activate on a specific function or method, shows which location in your code calls that function. This is similar to Find Refer ences in Java and C# tools. Figure 2.5 shows an example. CODE SUGGEST AND AUTOCOMPLETE Code autocomplete, although not always needed if you know the source and libraries well enough, is incredibly useful when you’re learning a new library and its features. It lets you see the available methods immediately, in the code, under the cursor. Is there a Sort method on the List class? Is there a way to get a list of char codes from a String? Code autocomplete will tell you this without your needing to leave the Edi tor—in fact, without leaving the text Editor pane. This feature is useful when you’re working with someone else’s code, whether it was written by someone else on your team or taken from other projects that you’re using. It could be said that you should not need autocomplete if you knew all the methods and their parameters by heart, but the reality of today’s open source frame works is that they change rapidly, and having method and parameter information directly in your code can only help. Code navigation, autocomplete, and error information are common tools that many developers have used elsewhere, and they’re unsurprising in their use. They’re worth noting because few JavaScript editors have these features. One of Dart’s design goals is to make developers’ lives better when developing web applications, and these three tools help to achieve this. 30 CHAPTER 2 “Hello World” with Dart tools 2.2.2 The relationship between Dart and HTML files Dart is designed to run in the web browser, either as native Dart or converted to JavaScript. To enable this conversion to JavaScript, your application needs to exist sep arately from the HTML file that defines the host web page. Fortunately, the Dart Edi tor is also designed to work this way: when you create a new project in the Dart Editor, you have the option of creating a boilerplate HTML file that contains a script tag to run your Dart application. Listing 2.2 shows the bare-minimum HTML that you need to enable your Dart application to run as either a Dart or a converted JavaScript application. It contains a script tag linking to your existing HelloWorld.dart script. It also contains another JavaScript script called dart.js, which detects whether the host browser contains the Dart VM. If the host browser isn’t Dart enabled, the script modifies any application/ dart scripts to application/javascript and appends a .js suffix to any src properties in those script tags: for example, it changes HelloWorld.dart to HelloWorld.dart.js. The following JavaScript version of your Dart app, as you’ll see shortly, is created by the dart2js tool. Listing 2.2 HTML file that can run your Dart app in both Dart and JavaScript Script referencing your Dart application file dart.js JavaScript file allows non Dart-enabled browsers to link to HelloWorld.dart.js instead The code built into the linked dart.js, which is included in the HTML, contains a snippet of JavaScript that checks to see whether the function navigator.webkitStartDart exists in the browser. You can also use this check in your code to determine whether you’re running in a Dart-enabled browser. Figure 2.6 shows the relationship between the host HTML file and your “Hello World” Dart script. 2.2.3 Running “Hello World” with Dartium From the Dart Editor, you can run this app the same that you did with the Dart VM ver sion. The Dart Editor detects that there is an associated HTML file and loads the app into the Dartium web browser, served from its own built-in server. This built-in server lists all the Dart applications that are currently available in the Editor, as shown in fig ure 2.7. “Hello World” uses the print() function to output a message. When running in a web browser, print() outputs to the browser’s debug console, similar to the JavaScript “Hello World” with the Dart Editor 31 HelloWorld.html Now that you have an element in your HTML page, you can modify your Dart script to update it. You’ll replace the print statement with one that gets the
element from the page. In order to do this, you need to use one of the built-in libraries, called dart:html. The dart:html library is designed to provide all the HTML APIs that you expect from the browser DOM, but in a consistent manner, with Dart-style API access; you’ll see much more of this library throughout the book. If you’re used to using jQuery with JavaScript, then the dart:html library should feel familiar. 2.3.1 Importing Dart libraries To import a library, you use the import statement. The import statement comes in three variations, which we’ll look at in more detail in chapter 5. The first is used to import core libraries, such as dart:html. In this case, you use the dart: prefix, in this form: import "dart:html"; Because this library is built into the Dart SDK, the tools know automatically where to find it. The second flavor of import is used to import third-party dependencies. It uses the package: prefix: import "package:unittest/unittest.dart"; We look at Dart’s unit-test framework in chapter 3. Libraries imported using the package: prefix are resolved using pub, Dart’s package manager tool, which is available for use on the command line or in the Dart Editor. Pub can pull dependencies from the internet using code repositories such as GitHub or Dart’s own pub.dartlang.org repository. In this form, it serves a purpose similar to that of Java’s Maven, .NET’s NuGet, and node.js’s npm tool. The most important commands are as follows: pub install pub update Importing libraries to update the browser UI 37 The first command installs the dependencies required, and the second updates them. Pub is a new tool and will likely evolve to provide a number of features, such as setting up boilerplate websites and frameworks. The final flavor of the import statement imports your own local or other local libraries by file path, for example: import "./myLibraries/helloLibrary.dart"; This form uses an implicit URI to access Dart libraries, which should be accessible by the Dart tools. When you convert Dart to JavaScript, all these imported libraries are pulled together into a single JavaScript file, containing only the code that is used. 2.3.2 Accessing DOM elements with dart:html Figure 2.10 adds import "dart:html"; into your Dart code and shows the modified main() function, which updates the status
with the text "Hello World". The dart:html library provides the query() function shown. The query() function is similar to jQuery’s $() function, which queries the browser DOM by using CSS selectors. CSS selectors CSS selectors are patterns you can use to pick items out of the browser DOM, and the two most common are #id and .class. There are plenty of tutorials available on the web, but the following is provided as a reminder. Given the following two lines of HTML
This is div number 1
This is div number 2
you can select both lines by using the CSS selector .myTextBlock (because they both share the same class), but you select the lines individually by using their ID val ues #firstLine and #secondLine. IDs should be unique, but multiple elements can share a class. HelloWorld.html
The Dart Editor can create these files for you when you use the New Application Wiz ard and select the Web Application option. The HTML file that’s created also has a useful JavaScript tag that loads the packList.dart.js (JavaScript version) of your app if the browser doesn’t natively support Dart. TIP Dart isn’t running? The Dart Editor Wizard creates a sample HTML file and a sample .dart file. Before you start writing your application, remove the example class from the .dart file and the

and

tags from the .html file; otherwise, you’ll see the “Dart is not running” message when you run your app in the browser. Now that you have the entry-point HTML file, which contains a and a