Dart by Example - Sample Chapter
Dart by Example - Sample Chapter
Dart by Example - Sample Chapter
ee
P U B L I S H I N G
C o m m u n i t y
D i s t i l l e d
E x p e r i e n c e
Dart By Example
$ 44.99 US
28.99 UK
pl
Davy Mitchell
Dart By Example
Dart By Example
Sa
m
Davy Mitchell
experience in many varied industries. He started out in the world of C++ and
progressed through the dot-com boom to the Microsoft.com era and into .Net, SQL
Server, and other web technologies.
In the past few years, he has worked on software installation, continuous integration,
build automation, and tooling, while also developing frontend interfaces. Davy is
passionate about both developer productivity and moving web applications forward.
He enjoys exploring new technologies, platforms, and open source, using Linux and
Windows operating systems.
Preface
The Web is undoubtedly a great platform for applications, and it continues to
develop at a rapid pace. The software development tools have progressed too,
but some technologies seem unsuited to modern demands. Most web developers
spend a good deal of time researching the current state of tools and libraries.
I discovered Dart when I wanted to write an HTML5 application and wanted to try
out one of the many new web languages everyone was talking about. I chanced upon
Dart and was soon hooked on the language and platform. Being able to compile a
client-side application before loading it in a web browser was life changing! There
were great tools and features available, and it was updated almost every week.
After learning Dart, I soon started a blog on it and enjoyed showcasing the language
with some fun colorful demos, news, and reviews, learning new aspects to blog
about. The community was great to interact with, and when the opportunity came
to write this book, I knew I had to do it. I find working with the Dart programming
language more enjoyable than any other language. I hope you have this experience
too, and write some great applications.
This book is designed to give you a clear picture of Dart's capabilities so that you are
able to evaluate its suitability for a task and are ready to approach the design of a
solution. We will be looking at Dart in a variety of projects, which will be, hopefully,
close to the real-world applications that you will end up writing.
Preface
Defining Dart
Dart is a language and platform for modern web applications that can run both in the
web browser and on the server. The Dart language, tools, and API allow innovative,
productive, enlightened, and talented developers (that's you!) to write scalable web
applications that make the best of the modern Web.
With Dart, you can take a leap forward in web development and tooling. It is a clean,
modern, yet familiar language syntax that runs on a platform created by the world's
leading virtual machine experts.
Dart is run as an open source project with a defined process for enhancement
proposals. It has flexible libraries with common documentation packaging, unit
testing, and dependency resolution. The language became an ECMA standard in
July of 2014, and does not require any plugin for end users to run as it is compiled to
JavaScript.
If that is not enough, you can bring your existing HTML, CSS, JavaScript skills, and
even code along for the rideDart plays nicely with others!
[1]
[2]
Chapter 1
In 2011, at the GOTO conference, the Dart language and virtual machine was
unveiled to the world. Dart is designed to be a "batteries included" projecta
complete stack for writing, compiling, testing, documenting, and deploying web
applications.
Developed by the Chrome team, the project was founded by Lars Bak (the developer
of the Java HotSpot VM and JavaScript V8 Engine) and Kasper Lund (a V8
developer). The aim was both to improve the open web platform by opening up new
avenues for high performance client web applications and to improve developer
productivity.
The upstart language was designed to have a familiar 'curly brackets' syntax
similar to Java, C-sharp, and JavaScript, run on both the client and the server, and
to support the full range of modern web browsers by being able to compile to
regular JavaScript. New language features were only added to Dart if they could be
compiled satisfactorily to JavaScript.
[3]
Dart is often referred to as DartLang to avoid confusion with other "darts." Keep
this in mind when searching the Web for better results. The Dart language, like
JavaScript, is not only meant for the web browser; it is also available for server
applications and command-line applications. Future targets are mobile applications
on iOS and Android.
That is the history, the challenge, and the reaction of the biggest Internet company
in the world. So, what is Dart all about, then? The remainder of this chapter will
compare and contrast Dart and JavaScript and take you into building your first Dart
application so that you can see for yourself.
The rest of this book will take you on a tour of Dart through a set of interesting
projects, exploring all of Dart's habitats. We will be building useful applications
straight away and using increasingly powerful features.
The downloads for all supported platforms (Linux, Mac, and Windows) are available
at https://www.dartlang.org/tools/download.html.The same location provides
information regarding building from source. Ensure that you download both the
SDK and Dartium (a specialist browser).
It is recommended that Mac users use the Homebrew system to manage the
installation and updates of Dart. Linux users can use a .deb if that format is
supported on their distribution, with ZIP archives being the alternative. Windows
versions are also supplied as ZIP archives.
[4]
Chapter 1
Windows users can download, install, and update the SDK and Dartium using the
Chocolatey installation system that is built on nuget and Powershell.
See http://chocolatey.org for more information.
[5]
WebStorm has a number of powerful features to help write our web applications:
A powerful debugger
[6]
Chapter 1
Stagehand can also be run from the command line, with the first step being to install
it as a command:
This step installs the stagehand command from the stagehand package:
mkdir aproject
cd aproject
stagehand web-full
This will create a folder of sample content based on the web-full template.
For full details of the current templates, see
https://pub.dartlang.org/packages/stagehand.
[7]
Description
dart2js
The tool that converts Dart into JavaScript so that it can run on any
modern browser.
Dartanalyzer
Analyzes the Dart source code for errors and suggestions. This is
also used by development environments to provide feedback to
users.
Dartdocgen
Dartfmt
The intelligent code formatter that makes your code tidy and
consistent.
pub
You may wish to place these tools on the system PATH so that you
can call them from anywhere on the command line. This is optional as
WebStorm provides an easy interface to these tools; however, many
developers find it essential to a good workflow.
For more detailed information on the installation and configuration of
pub, see
https://www.dartlang.org/tools/pub/installing.html
Also in this location is a snapshots folder. Most of the tools are written in Dart itself;
when they are started up and initialized, a binary image of the initialized state can be
stored and used for future executions of the program.
The snapshots are generated using the Dart executable and are mostly intended for
frequently used command-line applications in deployment.
Chapter 1
In the next chapter, we will build on this foundation for some flashier features and
graphical displays.
Downloading the example code
You can download the example code files for all Packt books you
have purchased from your account at http://www.packtpub.com.
If you purchased this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the files e-mailed
directly to you.
Description
pubspec.lock
pubspec.yaml
web/styles/main.css
web/index.html
main.dart
Unwrapping packages
From the preceding list, there is clearly a lot of structure and meta files for packages
in even a simple Dart project. The philosophy of the language is that libraries are
small, focused, and likely to be from different sources. They are also numerous and
update on different schedules, so version controls are importantdependencies are
hungry and must be fed.
[9]
You want your team members to be able to build and use your new Uber package
without dependency horrors! Likewise, you want the package you download off the
Internet to "just work" and reduce the effort required to write your application.
To look after all these packages, Dart has a tool called pub. This is a Swiss Army
knife tool that helps create, manage, and deploy your programs and packages. The
main home for Dart packages is the website https://pub.dartlang.org, where
numerous open source libraries are published.
If you are curious to know the origin of the name, "pub" is British slang
for a bar where people drink and play a game of darts.
A look at Pubspec
The pubspec.yaml has a curious file extensionYAML stands for Yet Another
Markup Language:.
name: 'TextEditor'
version: 0.0.1
description: A web based text editor.
environment:
sdk: '>=1.0.0 <2.0.0'
dependencies:
browser: any
Chapter 1
<body>
<div id="output">
<div id="toolbar">
TextOnTheWeb
</div>
<textarea id="editor" cols="80" autofocus>
</textarea>
</div>
<script type="application/dart" src="main.dart"></script>
<script data-pub-inline src="packages/browser/dart.js"></script>
</body>
</html>
The foot of this page is where the initial Dart file is specified. The main.dart file is
loaded and the entry point, the first function to be run, is the main() function.
If you have programmed in C/C++, C#, or Java, main is a
familiar starting or entry point to an application. The concept is
identical in Dart.
Let's work through the main.dart file section one at a time and discover some Dart
features along the way.
Importing packages
Dart features a keyword, import, to use other packages and classes in our current
code context. In this case, both are prefixed with dart: to signify they are from the
SDK:
import 'dart:html';
import 'dart:convert' show JSON;
The keyword show modifies the second import to only make the JSON property
sections of the dart:convert package. This limits the classes in the current
namespace and therefore helps avoid name clashes and developer confusion.
[ 11 ]
Variable declarations
The TextArea is central to our editor and will be referenced multiple times;
therefore, we will use a specific type for it rather than var. In contrast, JavaScript
declares variables with the all-encompassing var keyword.
TextAreaElement theEditor;
This declares a new variable called theEditor and declares it as the type
TextAreaElement. The dart:HTML package contains classes to cover the DOM and
the TextArea input element.
Dart has an optional type system, so it would be possible to declare var theEditor
and the program would still run successfully. By being specific with the type,
we gain clarity in the source code and we provide more detailed information to
developer tools, such as code editors and documentation generators:
void main() {
theEditor = querySelector("#editor");
theEditor
..onKeyUp.listen(handleKeyPress)
..text = loadDocument();
}
In the main function, we use the querySelector method from dart:HTML to connect
to the TextArea control (with the ID attribute set to editor) on the web page. Once
we have a reference to the control, we want to a) connect an event handler so that we
know when the user has typed something, and b) load any existing text and display it.
Because we are using the same object, we can use the cascade operator (..), which
helps us write very readable and flowing code. The preceding can be written as:
theEditor.onKeyUp.listen(handleKeyPress);
theEditor.text = loadDocument();
The more properties we set, the more we have theEditor cluttering up the code.
With the cascade operator, we can replace the object name with (..), and call the
method/set a property as before. One important point with the cascade operator is
that only the final use has a semi-colon at the end of the line.
[ 12 ]
Chapter 1
In contrast to JavaScript, there is no function keyword and we have void before the
function. The void keyword just means that this function does not return anything
when it is finished; it can be any class or type. As Dart is optionally typed, we could
omit void altogether.
Just a minute! Where are we going to be storing this text? After all, we have only
written a single HTML page and do not have a database connection or web service
to take care of the persistence. Fortunately, HTML5 has a simple key/value based
built-in storage feature called Local Storage that is well-supported by modern web
browsers. This operates in a similar fashion to a dictionary (sometimes called a map)
data structure.
In the next two functions, we will look at loading and saving from localStorage.
The HTML5 feature window.localStorage persistently stores data
with the client's browser. Unlike data stored in cookies, it does not expire
based on a date. The data is not lost when the browser window is closed
or the computer is switched off.
The amount of storage can vary per browser and according to user
settings, but the typical default value is 5 MB. This is plenty for our text
editor and many other types of applications.
[ 13 ]
We will store the text under the key MyTextEditor. The first time the user loads
up this page, there will be nothing in the local storage for our web page, so we will
check if it is empty or null before putting the value into the readings string variable.
JSON (JavaScript Object Notation) is an ECMA standard data format
that is based on a subset of JavaScript and is an alternative to XML.
For example:
{
"Name": "Davy Mitchell",
"LuckyNumber": 123,
"CarModel": null,
"Language": "English"
}
Finally, the saved document uses the local storage to keep our text safe. This time,
we are encoding the data into the JSON format.
[ 14 ]
Chapter 1
Dartium is a special build of the Chromium browser (the open source project behind
Google's Chrome browser) that contains the Dart virtual machine. Though not
recommended for day-to-day browsing, it is a full powerful modern browser to use
while developing Dart applications. As shown in the screenshot, it looks just like (a
very plain) Google Chrome.
If you are running on Ubuntu and receive a start up error mentioning
libudev.so.0, run the following command in a terminal to resolve it:
sudo ln -s /lib/x86_64-linux-gnu/libudev.so.1 /lib/
x86_64-linux-gnu/libudev.so.0
In WebStorm, right-click on the index.html file to bring up the context menu and
select the run index.html. This will start a local HTTP server for your application.
[ 15 ]
Once the application is running, type some text into the editor, and then close
the browser window. Then, run the program again and you should see your text
reappear once the page has loaded.
Once you have made the change, save the file and switch back to Dartium. Refresh
the page and the new version of the main function will run and the new title will be
displayed.
[ 16 ]
Chapter 1
Refresh the page and click the button to clear the existing text. One happy customer
and we hardly broke a sweat!
The WebStorm Dart plugin has a number of quick fixes to aid your productivity and
help avoid coding errors in the first place. They also encourage good design and
keeping to Dart conventions.
[ 17 ]
The main section to be concerned with is the "Installing the JetBrains Chrome
extension" section. This only has to be done once.
1. Click on the first line of the loadDocument function.
2. Next, open the Run menu and choose Toggle Line Breakpoint. A red circle
will appear to the right of the line:
3. Select index.html in the Project tab, then open the Run menu and choose
the Debug index.html menu.
4. Once Dartium opens, the loadDocument function should run and the
breakpoint should hit. The Debugger tab will appear in WebStorm.
5. The Debugger tab shows the call stack and values of current variables.
Under the Run menu and on the toolbar, the usual debug operations of Step
Into, Step Over, and return are available.
6. Before we take any steps, hover the pointer over the return statement line. A
tool-tip will appear to show that the string variable readings is currently
set to null.
[ 18 ]
Chapter 1
7.
Choose Step Over and the execution will move onto the next line.
8. Move the pointer over the return statement again, and the readings variable
is shown to be an empty string object.
9. Step Over until the end of the function, and the return variable will be set to
the text retrieved from local storage.
10. To get the application running again, use the Resume Program menu option
from the Run menu, or to stop it from running, select the Terminate menu
option.
In the Dart Analysis tab directly below the Dart code editor window, you will see a
warning that we have an unused import. This can be a useful tip once a project has
grown and code has been moved around into separate packages and classes. Import
lists can soon acquire clutter.
To call the JavaScript confirm dialog, we use the context object from dart:js in the
button click event handler. The context object is a reference to JavaScript's global
object:
void clearEditor(MouseEvent event) {
var result = context.callMethod('confirm',
['Are you sure you want to clear the text?']);
if (result == true) {
theEditor.text = "";
saveDocument();
}
}
[ 19 ]
The callMethod method can be used to call any JavaScript function available in
the scope of the pagenot just built in objects. In this case, the first parameter is
the name of the function we wish to call and the second parameter is the list of
arguments for that method.
Description
/**
In mentioning an identifier, place square brackets around the name. For example:
/// Returns double of [a] input.
int doubleANumber(int a){
//Assumes parameter valid.
return a * 2;
}
Take a short time to comment each function with the above style. Use a sentence
format and punctuation.
For more information on comment style and other coding conventions,
see the guidelines for Doc comments:
https://www.dartlang.org/articles/doc-commentguidelines/, and the Dart coding style guide: https://www.
dartlang.org/articles/style-guide/
[ 20 ]
Chapter 1
Summary
This chapter was focused on giving you the background story of Dart and getting to
work with the SDK to produce a useful application.
We have discovered how the JavaScript language and its development limits, leading
to the creation of the Dart open source project (centered around the https://www.
dartlang.org website), which is being developed as an ECMA standard and can be
used to write a range of application types from client to server and command line.
We have seen that Dart has a familiar syntax and powerful package management
tool called pub. WebStorm can be used to create, launch, and debug different types of
applications, and other IDEs and text editors have Dart language support, too.
We have worked through setting up a Dart development environment and wrote our
first application using HTML5 features. We saw how to navigate the structure of a
client-side web project and carry out debugging and development.
I am certain that the simple text editor that we have created is firing off ideas in your
mind of what to do next! In the next chapter, we will continue to look at client-side
Dart and add more features to the text editor, including some that will help us write
more, and better, Dart code.
[ 21 ]
www.PacktPub.com
Stay Connected: