Tải bản đầy đủ

Web programming with dart


For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.


Contents at a Glance
About the Authors��������������������������������������������������������������������������������������������������������������� xv
About the Technical Reviewer������������������������������������������������������������������������������������������ xvii
Acknowledgments������������������������������������������������������������������������������������������������������������� xix
Introduction����������������������������������������������������������������������������������������������������������������������� xxi
■■Chapter 1: Dart’s Flightpath So Far�����������������������������������������������������������������������������������1

■■Part I: Getting Started��������������������������������������������������������������������������������� 13
■■Chapter 2: Setting up Dart Correctly�������������������������������������������������������������������������������15

■■Part II: Dart Tools���������������������������������������������������������������������������������������� 31

■■Chapter 3: Making the Most of the Dart Editor����������������������������������������������������������������33
■■Chapter 4: Using Pub and dart2js to Compile Applications to JavaScript�����������������������75
■■Chapter 5: Application Launches�������������������������������������������������������������������������������������87
■■Chapter 6: Using the Dart Pub Package Manager�����������������������������������������������������������99
■■Chapter 7: Optimizing for Dart VM and Dartium������������������������������������������������������������115
■■Chapter 8: Cleaning up with Dart Formatter�����������������������������������������������������������������121
■■Chapter 9: Generating Dart Code Documentation����������������������������������������������������������125
■■Chapter 10: Monitoring Your Applications with Observatory����������������������������������������135

■■Part III: The Dart Language: Basics���������������������������������������������������������� 147
■■Chapter 11: The Dart Comment System�������������������������������������������������������������������������149
■■Chapter 12: Understanding Operators and Expressions������������������������������������������������159
■■Chapter 13: Mastering Dart’s Variables and Data Types�����������������������������������������������171

■ Contents at a Glance

■■Chapter 14: Flow Control Statements����������������������������������������������������������������������������205
■■Chapter 15: Working with Functions�����������������������������������������������������������������������������211
■■Chapter 16: A Syntax Summary and Cheat Sheet����������������������������������������������������������219

■■Part IV: The Dart Language: Advanced����������������������������������������������������� 223
■■Chapter 17: Processing Exceptions and Error Control��������������������������������������������������225
■■Chapter 18: Understanding Dart Classes�����������������������������������������������������������������������229
■■Chapter 19: Implicit Interfaces and Abstract Classes���������������������������������������������������243
■■Chapter 20: Implementing Generics and Typedefs��������������������������������������������������������251
■■Chapter 21: Using Dart’s Libraries���������������������������������������������������������������������������������257
■■Chapter 22: Leveraging Isolates for Concurrency and Multi-Processing����������������������273
■■Chapter 23: Asynchronous Programming with Dart������������������������������������������������������279
■■Chapter 24: An Advanced Syntax Summary������������������������������������������������������������������299

■■Part V: Dart and Other Web Technologies������������������������������������������������� 305
■■Chapter 25: Integrating Dart and HTML5�����������������������������������������������������������������������307
■■Chapter 26: Integrating Dart and CSS���������������������������������������������������������������������������321

■■Part VI: Dart and the Web Server�������������������������������������������������������������� 339
■■Chapter 27: Combining Web Services with Dart������������������������������������������������������������341
■■Chapter 28: Dart on the Server Side������������������������������������������������������������������������������367

■■Part VII: Dart’s Future������������������������������������������������������������������������������� 387
■■Chapter 29: Implementing Design Patterns and Creating Web Components�����������������389
■■Chapter 30: Developing a Dart App�������������������������������������������������������������������������������407


Welcome to Web Programming with Dart. Early, in our careers we came to recognize how our world would change
thanks to the Internet and especially to web applications. Every device we use in our daily lives uses the Internet
intensively. If we consider the different sizes and characteristics of devices and the different operating systems
available, we understand the complexity of software application development.
Web applications can help us with that. You develop an application and deploy it through different devices
and screen sizes, but to accomplish this task you need a programming language designed to understand the web
development complexity and run in different platforms. The applications must be highly optimized and support
numerous options: geo-localization, notifications, upload and play media files, or the interaction between users,
among others. We can develop web applications with those functionalities but the only way to develop such complex
applications is by using a high-level programming language specific to Web development with support for the latest
web technologies.
In this book you will master Dart, with a progressive and dynamic learning approach. It is one of the most complete
books on Dart written so far and provides the basics of developing web applications using Dart, an object-oriented and
structured language that supports interfaces, large hierarchy of classes, and optional typing. You will see examples
and even develop your first complete web application, step by step. You will learn how to integrate Dart with CSS3 and
HTML 5, combine Web Services with Dart, use Dart on the server side, implement design patterns and create web
components. The book had been written with consideration for programmers who want to learn this new programming
language but also for web designers because Dart can interoperate perfectly with HTML5 and CSS3.
This book is oriented to developers and web designers who want to develop high-level web applications and
are sick and tired of fighting with the creation of cross-platform web applications; for everyone who needs a new, yet
familiar web programming language for modern web applications and really big projects; and for developers who
need a typed language for a fast, secure, and easy development and debugging process.
In the book we will travel from the most basic to the most complex functions of this language but we will also
cover all the tools available to get the most of Dart. With this book you will know the language, how the tools work,
and you will see the core functions and libraries. We will show you the history behind Dart and how it came to us.
We will develop some UI animation samples for web, work with web services, server-side Dart applications, and the
new Polymer.dart library for the new HTML UI web component generation.

We will take a broad tour, showing the Dart basic and advanced functionalities.

You will learn the tools that come with Dart SDK and the main, most important libraries.
Additionally you will work with the newest Polymer.dart library for web component creation.

You will be able to develop your own command-line and server-side applications and, of
course, web applications with Dart.


Chapter 1

Dart’s Flightpath So Far
In this chapter we will introduce you the Dart programming language, including how Dart functions and what Dart is.
We’ll see what structured programming is and how we can take advantage of it using Dart.
Dart brings us great advantages for web development. We will see these advantages compared to JavaScript or
jQuery on the client side as well as Dart’s most interesting functionalities.

What is Dart?
Dart is an open-source, structured, and flexible programming language developed by Google, particularly oriented for
web development, but not exclusively. This new programming language has arrived to make programmers lives easy,
allowing them to develop more complex web applications with better maintenance and improved performance.

■■Note  Structured programming is a programming model aimed at improving the clarity and the quality of the code,
cutting down development time, using subroutines and three basic structures: block structures, selection structures (if
and switch), and looping structures (for and while loops).
Behind Dart are Lars Bak and Kasper Lund, two of the authors of the V8 JavaScript engine for Google Chrome.
For that reason the performance and efficiency of the language were two factors that were very important at the
moment of developing this language.
Gilad Bracha was also involved in the creation of Dart. Bracha is the author of Newspeak Programming Language,
co-author of Java Specifications and the second edition of the Java Virtual Machine Development.
Dart is a class-based, object-oriented language with simple inheritance. Dart also supports interfaces, abstract
classes, and optional typing.
Don’t worry about all of those terms. We will see everything in depth step by step and you will enjoy all of those
advantages in a very simple way.
We have commented that Dart is an alternative for web development, especially in the client side. Currently the
trend is that, programmers try to develop most of the tasks in the client side allowing the server to be smaller and
faster. Thus, with a very simple, lighter server it can manage more requests per second.
Despite what it seems Dart was not developed to replace JavaScript, however it was developed to offer an
additional, modern option for web development with better performance and above all for big projects in which the
maintenance process is complicated.
Dart has a C-style syntax, thereby to all programming languages that inherit from it. So, if you have previously
worked with JavaScript, Java, PHP, C++, Objective C, or C#, you would be very happy because you now know Dart.


Chapter 1 ■ Dart’s Flightpath So Far

Dart is the best option for really big web projects with special importance in the client side. This programming
language allows for better organization of the code and you can maintain your project more easily than with others
programming languages, such as JavaScript.
Dart produces a very readable code and runs in mainstream browsers (you can compile your Dart code to
JavaScript and run it in all of the modern web browsers).
Dart code runs over DartVM (Dart Virtual Machine), which is two times faster than JavaScript. As you can see
in Figure 1-1, Dart code compiled to JavaScript is faster than native JavaScript code running on V8 engine for the
Tracer test.

Figure 1-1.  Dart VM, dart2js, and JavaScript V8 performance

■■Note  You can learn more about Dart performance in https://www.dartlang.org/performance/


Chapter 1 ■ Dart’s Flightpath So Far

Advantages to Using Dart
One of the main advantages is its high performance. Currently, in some benchmarks, even running Dart code
compiled to JavaScript is faster than JavaScript native code running on V8. Another advantage is its simplicity and
clarity when you use it and most importantly when you have to learn it. Dart offers unimaginable possibilities when
you need to develop and maintain big, complex applications.
Furthermore, Google Dart developers and the open-source community have created great documentation,
including tutorials and samples. This is welcome when you need to start with a new programming language.
One great advantage is the ability to use a full IDE (Integrated Development Environment) just out of the box.
This IDE is known as Dart Editor where you can find all the SDK, classes, and methods with their documentation, a
very powerful debugger, and tools to compile and test your applications.
Dart Editor is not the only IDE you can use to work with Dart. Dart has official support for other editors like
Intellij / Webstorm, Eclipse, or Sublime Text 2 and 3.
Asynchronous programming is one of the most powerful features of this new language. We will dive into this subject
in coming chapters but for the moment we want to explain the basic idea of the asynchronous programming in Dart.
The asynchronous programming is made in Dart thanks to Future API, which allows you to run tasks and
processes in the background without waiting to get the results of these processes. The results will come later and
you’ll be able to get those results and make other tasks, change the layout, or show information to the user.
We don’t want to end this section without mentioning a very interesting and powerful advantage. You can
use Dart to develop web applications, as we previously have said, but in addition, you can use Dart to develop
command-line applications and server-side applications. You only need to have DartVM installed on your system
to run your Dart applications. You can run your Dart apps on Mac, Windows, and Linux.
But not all aspects of Dart are advantages. Regardless of the documentation we have mentioned, you cannot
find a lot of documentation as it applies to other programming languages like PHP or JavaScript. Dart is a very young
programming language, having just reached its 1.0 stable version at the end of 2013. With the new releases 1.6 and 1.7
everything would be easier. Google and the community are making efforts to improve the Dart documentation and,
we also hope to help meet the shortfalls of documentation and make the learning task easy and fun with this book.

Dart’s Origins
The programming paradigm has changed a lot over the past few years. To start with the server was in charge of doing
everything. When a user visits our web page (as shown in Figuserver makes database queries, makes access validatre
Figure 1-2), the ion processes, builds the HTML document, and loads external resources as CSS, JavaScript scripts,
images, and videos. This is happening in web applications developed with PHP, Python, JSP, or Ruby.

Figure 1-2.  Standard server-client requests scheme


Chapter 1 ■ Dart’s Flightpath So Far

Every link you visit makes all the processes run again and finally displays an HTML document rendered by the
client browser. This makes every request very expensive each time the client wants to view any resource on the server.
Thinking how the web services have changed during last years, the emergence of new mobile devices and social
networks, there are thousands of people trying to request something from our server.
We will have a serious problem trying to attempt all those requests. Our server won’t be able to meet all the
demands because every request uses a lot of time and resources. Can we do certain tasks on the client browser to
allow our server to be lighter? Can we use the CPU, memory, and all the resources on the client to make certain
New HTML, CSS, and JavaScript versions make it possible. Every time you browse through the Internet, access
a web service, or login to your social network profile, the server sends to your browser several scripts that use
your browser, your computer, and create jobs on your web browser. This makes server life easier. See Figure 1-3 to
understand how the client applications make requests to the servers.

Figure 1-3.  New asynchronous server-client data requests
These applications running on the client browser make asynchronous data requests, avoiding blocking the
client, to the server. The client won’t wait for the request to finish and the browser won’t appear to stop responding
while waiting for a blocking request. The client application could make several requests and they’ll get the server
information and with that information they can manipulate and change the web page showing or hiding different
parts of the document. Thus we can simplify server requests and our server will take less time to complete its job,
attending to more clients per second.
Thanks to these asynchronous data requests made with JavaScript and the HTML evolution we can develop a lot
of process in the client side in a very simple way. We can forget old plugins like ActiveX, Java Applets, and Adobe Flash
Player, because JavaScript is standard and supported by all the modern web browsers.
Imagine now an application like Gmail or Google Docs that can develop all the web user interfaces, manage all the
requests, and all the events on the client web browser, that would be a very hard task to accomplish. The maintenance
process of an application like Gmail would be hard and expensive even if you use JavaScript frameworks.
JavaScript was not designed for those purposes, as it is not robust enough and the code will be unreadable and
obscure when you begin working with callbacks. Additional JavaScript suffers really big problems with memory
When they have to develop applications like Gmail, the Google developers end up asking if JavaScript was really
the programming language for that purpose. They will try to find other alternatives like GWT. With GWT they acquire
a more structured approach, but it had very poor performance for the web.
Dart was created in response as a programming language that combines both worlds as it has the dynamism of
JavaScript with the power and structure of languages like C# or Java.


Chapter 1 ■ Dart’s Flightpath So Far

Dart will let you develop big, complex applications as you will do with Java, Python, or C#. In addition, with Dart
you could develop small scripts to simplify the concrete tasks on your web pages as you can do with JavaScript.
Currently Dart can run on all the major, modern web browsers, but previously Dart code needed to be compiled
to JavaScript (dart2js). In the near future Dart will run directly on our web browsers thanks to DartVM and we don’t
need to compile it in advance. Google Chrome plans to include DartVM so you can run your Dart applications on that
browser with all the power and performance we have described.

Converting From Other Programming Languages
We have explained that Dart was designed with consideration for complex web applications, development and
maintenance processes, and with special attention to its performance. In depth understanding of the language is the
most important task in your TODO, which is why we wrote this book. However if you have previous experience with
JavaScript or the jQuery JavaScript framework we would like to show you quickly some simple examples between
JavaScript, jQuery, and Dart.

Dart Names are Simpler and More Structured
As you can see in Table 1-1 the names were simplified, more structured, and more consistent using CamelCase
for capitalization.
Table 1-1.  Dart Vs JavaScript. The names











Searching for DOM Elements is Easier
With the advent of jQuery several JavaScript frameworks were inspired to query the DOM with CSS selectors
(Dart does this too). The search DOM elements methods (Table 1-2), were cleaned up and it has only two methods
compatible with the new HTML5 standard querySelector() and querySelectorAll().
Table 1-2.  Dart vs. JavaScript and jQuery. DOM elements

















Chapter 1 ■ Dart’s Flightpath So Far

Dart Has Real Data Collections
Dart has different data types to represent data collections, Lists, Maps, and Sets.
In JavaScript, the data collections of DOM elements when you retrieve elements using, for example,
getElementsByTagName are different from the built-in JavaScript Array type.
In Dart, this is easier and the methods that manipulate the DOM (for example, children, nodes, or using
querySelectorAll) always return real data collections as Lists, Maps, or Sets. No matter what method you use you
will always have built-in data collections.
Using dart:html, the Dart library to manipulate the DOM, when you retrieve a list of elements by tag name you
will have this kind of structure List.

import dart:html
void main() {
List my_divs = document.querySelectorAll('div');

As a result, several JavaScript methods have been cleaned up. For example, in JavaScript when you retrieve an
element you have a lot of different methods to manage its attributes. As you can see in Table 1-3, with Dart you can
work with the attributes of an element as you do with a regular Map, because Dart stores all the attributes in a Map.
Table 1-3.  Dart Vs JavaScript and jQuery. Real Data collections










elem.setAttribute(‘name’, ‘value’)

elem.attr(‘name’, ‘value’)

elem.attributes[‘name’] = ‘value’




Constructors to Create New DOM Elements
If you want to create new DOM elements, in JavaScript (jQuery use the same method as well for performance) you can
do it using createElement(). With Dart, because it’s an object-oriented language, you can use a different constructor
for each different DOM element (Table 1-4).
Table 1-4.  Dart vs. JavaScript and jQuery. New DOM elements






new DivElement()


new InputElement(type:‘checkbox’)


Chapter 1 ■ Dart’s Flightpath So Far

Dart Improves and Unifies the Events System
Events are the most important and useful to change, as you will find in Dart. The development team has changed how
the events are bound with event handlers.
The DOM has two ways to work with events. The old one that binds one event handler with an element by setting
one of the on properties of the element and the new one using addEventListener() and removeEventListener() that
allows multiple listeners for the same event.
In Dart, things are simplified. All the on element properties are removed and it uses API Stream that provides a
unified event model (Table 1-5).
Table 1-5.  Dart vs. JavaScript and jQuery. The events system




elem.addEventListener(‘click’, (event) =>
print(‘click’), false);

function(event) {});

var eventListener = elem.onClick.
listen((event) => print(‘click’));

elem.removeEventListener(‘click’, listener);



For each event type on the DOM, each element has a property to manage that event, such as onClick,
onMouseOver, and onBlur.

Say Goodbye to Vendor Prefixes
When you are working in the client side, you know you need a widely standard application and you need it to work
in all the web browsers. For that reason programmers usually work with frameworks that let them have standard
problems fixed.
Working inside the browser you sometimes will find some methods have different names for each different
browser and its rendered engine.
For instance, if you need to check if the browser supports IndexedDB you should ask for window.indexedDB or
window.mozIndexedDB (Firefox browser) or window.webkitIndexedDB (Safari and Chrome) or window.msIndexedDB
(Internet Explorer).
In Dart you won’t find those options. There is only one standard way to call this method and check if indexedDB
is supported in the client browser: you will only need to call window.indexedDB.
With this simplification we will write better, more readable code and are prone to errors. We will develop
applications with multi-browser support without having a lot of checks to do.

Future-Based APIs
When you want to write asynchronous code using JavaScript you need to use AJAX and callback functions as the
return result for your functions or use the callbacks as parameters for other functions. So, you will end up chaining
functions. When you are working in a very complex and big project using this system produces unreadable code that
is very prone to errors. The maintenance process would be unbearable.
Dart has incorporated Future class into its SDK. This class allows you to isolate in an object-oriented way
asynchronous return results as built-in functions.
This is one of the major advantages of the language; everything is asynchronous in Dart. You will have to change
the way you’ve been working but once you’ve done so you will never go back to the old callback hell.
Future API makes your code more readable, cleaner, and allows you to make asynchronous tasks in a very
simple way.


Chapter 1 ■ Dart’s Flightpath So Far

If you had this kind of JavaScript code:

function showResult(xhr) {
if (xhr.readyState==4 && xhr.status==200) {
function getResult() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = showResult(xhr);
xhr.open(‘GET’, ‘http://www.google.es’, true);

Now with Dart your code looks like this.

void getResult() {
.then((resp) => querySelector('result').setInnerHtml(resp));

Undoubtedly this is an amazing improvement that makes your job easy. As we mentioned the Future objects are
used all the time in the Dart SDK; you will use them in your applications too, because Dart has been designed to be
totally asynchronous.

Dart has a great clean up and new organization regarding DOM libraries. Thanks to this new organization the library
for managing DOM and HTML is lighter and simpler.
All the classes and methods for indexedDB, audio, web_sql, and svg have been taken from DOM basic library
and new libraries have been created for each different purpose. Furthermore in these new libraries they have cleaned
up names, deleting unnecessary and repetitive prefixes. Now each library has its own namespace making it much
simpler and more efficient.

■■Note A namespace is often used to refer to a collection of names that we have defined and all the names have
unique identifiers.

Cross-Browser Consistency
We have already mentioned, in Dart all the vendor prefixes have been deleted, and all the libraries have been
simplified and reorganized. Those changes allow us to have a simple code that runs all over the web browsers.
You don’t need to add an additional framework to your projects, so you don’t have an additional layer between
your code and built-in language functions.

■■Note  Cross-Browser means web pages or applications that run and work in the same way in all the web browsers.


Chapter 1 ■ Dart’s Flightpath So Far

Cascaded DOM Construction
You will use this operator a lot. In the beginning Dart did not have this operator and it was included to simplify your
daily job when you are working with DOM elements.
It’s very common when working with HTML elements to decide to change several properties or attributes for
one element. This kind of task produces big code blocks, repeating the same element name several times. Our code
becomes illegible.
If you have to repeat the element name maybe ten times, instead of defining a very descriptive name for that
element you will use a very shortened name, that will make our code less readable.
For instance, in JavaScript you will have this code.

var el = document.createElement("input");
el.setAttribute("id", "my_identifier");
el.setAttribute("type", "number");
el.setAttribute("value", "my_value");
el.setAttribute("name", "my_name");

With Dart you could set all the attributes at the same time and you could use more descriptive names for the
element. Those advantages make your code more readable, auto-documented, and small.

var inputNumberOfChildren = new InputElement(type: 'number')
..id = 'my_identifier'
..value = '0'

Why Dart is Perfect for Web Development
We have various aspects we think make Dart the perfect platform for building web pages and web applications,
including Asynchronous programming with Future API, cross-browser SDK, User experience, responsive design or
mobile friendly, and the way you can control your applications and debug them from the start of your coding.
The asynchronous programming on web browsers arose a few years ago thanks to an Internet Explorer bug
related to XMLHttpRequest object. This bug allowed developers to make requests to the server in background mode
and once the results are ready they could use them to change the layout or run other tasks.
The most important part here is “in background mode” because the web page didn’t wait and didn’t freeze
waiting to finish this task. The developers can now run a lot of tasks asynchronously and leverage the power of the
browser to build the most important parts of the application like the user interface or show initial information quickly
to the user, improving the user experience.
Once the asynchronous tasks are finished, the developers use this information to make other tasks, show more
information to the user, or change the layout showing new blocks.
Imagine a web application like Twitter, Facebook, or Google+. You sign in and quickly you see the basic layout,
the application menu with all the options, and few seconds later you begin to see your latest posts. While the browser
is rendering the basic layout it made an asynchronous request to the server to get the latest news or posts. When this
request has finished the application gets the retrieved information and uses it to build new HTML blocks with this
This asynchronous programming is now available in all modern web browsers; with JavaScript you can use
the XMLHttpRequest object and build your asynchronous applications. Dart simplifies it a lot and gives this
asynchronous programming the structured touch necessary for building complex and big web applications. The
Future API is responsible for this. We think this is one of the most important parts of the language; in fact, all the SDK
uses this same philosophy.


Chapter 1 ■ Dart’s Flightpath So Far

Thanks to this API you will build the most powerful asynchronous web applications in the easiest way ever. No
matter how big your application is, with this API you can maintain your applications in the easiest possible way so far.
Until now developing web applications was like driving a car without wheels, you have brakes, an accelerator,
and gears but you don’t have the ability to handle the car easily. If you have developed web applications you know
what we’re talking about. You have the languages and the browsers but you couldn’t be agile with your developments.
For the few past years the browsers evolved rapidly making important changes for web developers.
Now we have Google Chrome with its Chrome Developer Tools, a very useful and important tool to make
your web developments easier and allow for more control over your applications. Safari and Firefox, among other
browsers, have similar applications and a lot of plugins and addons to improve your productivity.
The only thing we needed was for the programming languages to evolve too and Dart did. You now have
everything you need all in one place, making your development experience amazing and extremely easy for anyone
who wants to come up to Dart.
We consider this one of the most important features for a modern web programming language. Don’t worry if
your applications would run properly in all of the web browsers. Dart is a cross-browser language.
Your applications would be mobile friendly, with a responsive design, from the moment you start coding. In the
present days is incomprehensible develop a web page, a web application with no support for all the mobile devices
you can find outside. When a user visits your website from his or her phone and the web page he’s visiting does not
adapt the content to that device, the user could not view your web page as he expects. That bothered the user and you
probably lost this user forever.
We need to write better code, we can do better and we need to improve the UX (User Experience). The only way
to accomplish this task is using a better programming language; one with great tools and good manners to develop
your applications, thinking in all those aspects but not making harder your development process.
Your development experience as the user experience we’ve mentioned must be great and simple; you only have
to focus on your application and how it must works. And then your application would adapt and fit perfectly the
target device, no matter if it is a phone, a tablet, an old small screen or a new one really big screen. Every device would
render your web application according to the users’ device, as shown in Figure 1-4.

Figure 1-4.  The application adapts to different devices to provide an optimal viewing experience
As you will see in the remaining chapters Dart has a lot of great tools to improve your development and your
productivity. With those tools, and with a very simple and structured programming language you could control your
applications as long as you start coding.
You can debug your applications step by step as you could do with other languages and platforms in a very
simple way that lets you have the control of your applications.


Chapter 1 ■ Dart’s Flightpath So Far

No more black boxes in which you don’t know how the things were working, no more using fools alerts or console
logs like you have to do with JavaScript to test and debug your applications.
With the browser’s developer tools everything was a very easy but you have to write your code, save it, load your
web page or your application in the browser, open its developer tools, and add your breakpoints to the methods you
want to test. Every time you need to test something you need to repeat that process; every time you bugfix something
you need to repeat the process. It’s very annoying.
This kind of work would be a memory of the past thanks to Dart. You only need to write your code in Dart Editor,
set your breakpoints, and run it; that’s all, and you could go step by step through your entire application, method by
method, class by class or even entering from one library to another. During your debug process you always have all the
local variables and objects and you can see everything that is happening.
We will see all of this mentioned in action in the coming chapters and we bet you will love these features too.

In this chapter we have learned:
Dart is a programming language:

Developed by Google

It would be an alternative to JavaScript


With high performance

It has its own virtual machine called DartVM

It produces simple code and simplify maintenance tasks

It follows structured programming model


It could be compiled to JavaScript and run it in all the mainstream browsers.

It emerged to support new trends that keep the server-side simple and add complexity
in the client side.


Part I

Getting Started


Chapter 2

Setting up Dart Correctly
Now that you know and understand more about using Dart and all the utilities it brings to you, it’s time to roll up your
sleeves and start working with it.
We understand you may not know anything about the language yet, such as its syntax or quirks, but we think it’s
very important to show you the main tool you will use working with Dart, in order to take a comprehensive view of the
language and the tools so you can make your tests.
Dart is extremely easy to start and has a lot of tools and very powerful SDK, but the most important advantage
is that you only need to download one simple compressed ZIP file to start working with it. The first thing you need to
do is get the software development kit (SDK) and the code editor (Dart Editor). In this chapter we will download and
install them to become better familiar with our new software development environment. Then we’re going to open
our first sample application, just to have a look at the code.

Downloading and Installing the Software
The first thing you must do is visit www.dartlang.org, the official Dart programming language site, and get the latest
version of the SDK and Dart Editor. The home page shown in Figure 2-1 will automatically detect your operating
system and version in order to offer you the direct link to download everything you need to start with Dart.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-1.  Dartlang.org home page to download the tools
Clicking on the download link we will start the download of a compressed ZIP file with Dart SDK and Dart Editor.
After downloading the file, you only need to unzip it. No installation is required. You do not need to follow
any installation wizard steps and wait for a long time while the installation wizard does its job to enjoy your new
development environment. Just download it, unzip into the directory you selected, and run it by clicking DartEditor
application icon. You now have all you need to start with Dart.
Once you’ve unzipped the downloaded file you will see a directory structure similar to Figure 2-2.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-2.  Directory structure after unzipping the downloaded file
At this moment we won’t go into details of these directories, we just want you to start seeing and try Dart, so
double click on the Dart Editor icon and it starts running.
This is the code editor you will use when you work with Dart. It is based on Eclipse, so if you know or have
previously worked with Eclipse this will be very familiar.

■■Note  Dart Editor is a Java based application. You must have Java 6 or higher for Dart to work properly. Go to www.java.com
to download and install Java on your system.
When you try to run Dart Editor for the first time and don’t have Java SE 6 runtime, Dart Editor will offer to install
Java for you.

Setting Up a Previous Version of Dart Editor
If you have previously downloaded Dart Editor, you must check your version in order to work with the latest version of
Dart SDK and Dart Editor. You can check your Dart version on Dart Editor menu and select About Dart Editor menu
item, as shown in Figure 2-3. The About Dart Editor dialog will be displayed and you could check your version and if
there is another most recent version available.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-3.  Getting the new Dart version
Click on the Download update … button to get the latest and most recent version. Once the download has
finished, you can apply it.
You also can check your version by clicking on the top right icon, as shown in Figure 2-3. This icon is the
shortcut for Dart Editor Preferences. When a new version is available you can see a green arrow near that icon.
Clicking on that icon shows you the Preferences dialog (Figure 2-4) with the new update available.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-4.  Update preferences dialog to get the new Dart version
In this dialog you can get the latest stable version of Dart by clicking on Download update … button and you can
check the option Download updates automatically to stay updated.
When the latest version has been downloaded and is ready to install simply click on the Apply update button,
as shown in Figure 2-5.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-5.  Applying the new downloaded version
This action will replace all the content of your installation directory with the new version just downloaded.
Don’t worry about your Dart Editor preferences because all of them are saved in a different place in your user home
directory to avoid overriding them.
In order for this update to take effect Dart Editor will be closed and reopened again when you apply the update so
be careful and remember to save all your work before applying a new update.

Dart Editor and the Software Development Environment
Dart Editor gives you everything you need; you can view the SDK directly on the editor. It helps you to develop your
code and allows you to run and test your applications.
In the Dart installation directory, double click on the executable file Dart Editor
. The application will be
opened displaying the Welcome window, as shown in Figure 2-6.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-6.  Dart Editor Welcome window

Opening and Running an Example
Dart Editor includes examples in the welcome page. In the section Demos of Dart simply select the first one and Dart
Editor will do the rest.
The editor displays the contents of Sunflower.dart (Figure 2-7) and file view (left panel) shows the directory
structure with the files of the Sunflower application.


Chapter 2 ■ Setting up Dart Correctly

Figure 2-7.  Initial view in Dart Editor of our first sample application: Sunflower
We do know you’re eager to get started, so let’s see this example running. Look at the Dart Editor toolbar and see
a round green button
. This is the Run button, for running applications from Dart Editor.
The Sunflower application is a web application, so when you click on the button to run, the application will run
in the web browser as if it were an HTML web page, as shown in Figure 2-8.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay