Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Dart
Learning Dart

Learning Dart: Dart is the programming language developed by Google that offers a new level of simple versatility. Learn all the essentials of Dart web development in this brilliant tutorial that takes you from beginner to pro.

eBook
£27.98 £39.99
Paperback
£49.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Dart

Chapter 2. Getting to Work with Dart

In this chapter you will get a firm grasp on how to program in Dart. The code and data structures in Dart and its functional principles are explained by exploring practical examples. We will look at the following topics:

  • Variables – if, how, and when to type them
  • What are the basic types that you can use?
  • Documenting your programs
  • How to influence the order of execution of a program
  • Using functions in Dart
  • How to recognize and catch errors and exceptions?

You will see plenty of examples, also revisiting the code from Chapter 1, Dart – A Modern Web Programming Language. Because most of this will be familiar to you, we will discuss these topics succinctly and emphasize only that which is new or different. You can refer to http://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html if you need more detailed explanations. We encourage you to play with the code examples, the best way to become familiar with Dart. The full API reference...

Variables – to type or not to type

In our first example (Raising rabbits) in Chapter 1, Dart – A Modern Web Programming Language, we started by declaring a variable rabbitCount dynamically with var, and then in the second version we gave it a static type int (refer to the file prorabbits_v1.dart and prorabbits_v2.dart in Chapter 1, Dart – A Modern Web Programming Language) and concluded that typing is optional in Dart. This seems confusing and has provoked a lot of discussion: "is Dart a dynamic language like Ruby or JavaScript, or a static language like Java or C#?" After all, some of us were raised in the (static) belief that typed variables are absolutely necessary to check if a program is correct, a task mainly performed by the compiler (but the Dart VM has no separate compiler step, and dart2js, the Dart to JS compiler, doesn't check types because JS is fully dynamic).

It turns out that no mainstream language actually has a perfect type system (static...

Built-in types and their methods

Like Ruby, Dart is a purely object-oriented (OO) language, so every variable in Dart points to an object and there are no primitive types as in Java or C#. Every variable is an instance of a class (that inherits from the base class Object) and has a type, and when uninitialized has the value null. But for ease-of-use Dart has built-in types for numbers, Booleans, and strings defined in dart:core, that look and behave like primitive types; that is, they can be made with literal values and have the basic operations you expect (to make it clear, we will use full typing in builtin_types.dart, but we could have used var as well).

A String (notice the capital) is a sequence of Unicode (UTF-16) characters, for example:

Built-in types and their methods

They can be indicated by paired ' or " (use "" when the string contains ' and vice versa). Adjacent string literals are concatenated. If you need multiline strings, use triple quotes ''' or ""&quot...

Documenting your programs

Documenting an application is of utmost importance in software engineering and Dart makes this very easy. The single-line (//) and multiline comments (/* */) are useful (for example, to comment out code or mark lines with // TODO), and they have counterparts /// and /** */ called documentation comments. In these comments (to be placed on the previous line), you can include references to all kinds of objects in your code (classes, methods, fields, and so on) and the Dartdoc tool (in Dart Editor go to Tools | Generate Dartdoc) will generate HTML documentation where these references become links. To demonstrate we will add docs to our banking example (refer to banking_v2doc.dart):

/**
 * A bank account has an [owner], is identified by a [number]
 * and has an amount of money called [balance].
 * The balance is changed through methods [deposit] and [withdraw].
 */
class BankAccount {
  String owner, number;
  double balance;
  DateTime dateCreated, dateModified;
...

Changing the execution flow of a program

Dart has the usual control structures with no surprises here (refer to control.dart).

An if...else statement (with an optional else) is as follows:

var n = 25;
if (n < 10) {
  print('1 digit number: $n');
} else if (n >=  10 && n < 100){
  print('2+ digit number: $n'); // 2+ digit number: 25
} else {
  print('3 or more digit number: $n');
}

Single-line statements without {} are allowed, but don't mix the two. A simple and short if…else statement can be replaced by a ternary operator, as shown in the following example code:

num rabbitCount = 16758;
(rabbitCount > 20000) ? print('enough for this year!') : print('breed on!');   // breed on!

If the expression before ? is true, the first statement is executed, else the statement after : is executed. To test if a variable v refers to a real object, use: if (v != null) { … }.

Testing if an object v is of type T is done with...

Using functions in Dart

Functions are another tool for changing the control flow; a certain task is delegated to a function by calling it and providing some arguments. A function does the requested task and returns a value; the control flow returns where the function was called. In Java and C#, classes are indispensable and they are the most important structuring concept.

But Dart is both functional and object oriented. Functions are first-class objects themselves (they are of type Function) and can exist outside of a class as top-level functions (inside a class they are called methods). In prorabbits_v2.dart of Chapter 1, Dart – A Modern Web Programming Language, calculateRabbits is an example of a top-level function; and deposit, withdraw, and toString from banking_v2.dart of this chapter are methods, to be called on as an object of the class. Don't create a static class only as a container for helper functions!

Return types

A function can do either of the following:

  • Do something...

Recognizing and catching errors and exceptions

As a good programmer, you test your app in all possible conditions. Dart defines a number of errors for those things that you should remedy in your code, such as CastError when a cast fails, or NoSuchMethodError when the class of the object on which the method is called does not have this method, and neither do any of its parent classes. All these are subclasses of the Error class, and you should code so that they do not occur. But when something unexpected occurs while running the app, and the code cannot cope with it, an Unhandled Exception occurs. Especially input values that are read in from the keyboard, a file, or a network connection can be dangerous. Suppose input is such a value that is supposed to be an integer (refer to exceptions.dart); we try to convert it to an int type in line (1):

var input = "47B9"; // value read from input,should be an integer
int inp = int.parse(input);                 (1)

While running the program...

Variables – to type or not to type


In our first example (Raising rabbits) in Chapter 1, Dart – A Modern Web Programming Language, we started by declaring a variable rabbitCount dynamically with var, and then in the second version we gave it a static type int (refer to the file prorabbits_v1.dart and prorabbits_v2.dart in Chapter 1, Dart – A Modern Web Programming Language) and concluded that typing is optional in Dart. This seems confusing and has provoked a lot of discussion: "is Dart a dynamic language like Ruby or JavaScript, or a static language like Java or C#?" After all, some of us were raised in the (static) belief that typed variables are absolutely necessary to check if a program is correct, a task mainly performed by the compiler (but the Dart VM has no separate compiler step, and dart2js, the Dart to JS compiler, doesn't check types because JS is fully dynamic).

It turns out that no mainstream language actually has a perfect type system (static types don't guarantee program correctness...

Left arrow icon Right arrow icon

Description

Mastering Dart by Projects is a step-by-step guide that aims to give you hands-on knowledge about programming in Dart using an example-based approach.If you want to become a web developer, or perhaps you already are a web developer but you want to add Dart to your tool belt, then this book is for you. This book assumes that you have at least some knowledge of HTML and how web applications work. Some previous programming experience, preferably in a modern language like C#, Java, Python, Ruby, or JavaScript, will also give you a head start. You can also work with Dart on your preferred platform, be it Linux, Mac OS X, or Windows.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 02, 2014
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697422
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 02, 2014
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697422
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 128.97
Learning Dart
£49.99
Mastering DART
£41.99
DART Cookbook
£36.99
Total £ 128.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Dart – A Modern Web Programming Language Chevron down icon Chevron up icon
2. Getting to Work with Dart Chevron down icon Chevron up icon
3. Structuring Code with Classes and Libraries Chevron down icon Chevron up icon
4. Modeling Web Applications with Model Concepts and Dartlero Chevron down icon Chevron up icon
5. Handling the DOM in a New Way Chevron down icon Chevron up icon
6. Combining HTML5 Forms with Dart Chevron down icon Chevron up icon
7. Building Games with HTML5 and Dart Chevron down icon Chevron up icon
8. Developing Business Applications with Polymer Web Components Chevron down icon Chevron up icon
9. Modeling More Complex Applications with Dartling Chevron down icon Chevron up icon
10. MVC Web and UI Frameworks in Dart – An Overview Chevron down icon Chevron up icon
11. Local Data and Client-Server Communication Chevron down icon Chevron up icon
12. Data-driven Web Applications with MySQL and MongoDB Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(10 Ratings)
5 star 50%
4 star 40%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Si Dunn Jun 20, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I generally agree with the four-star and five-star reviews that have been posted here. "Learning Dart" does deliver a good overview for inexperienced developers and experienced developers alike. I have tested some of the code samples on Linux and Windows machines and have enjoyed working with the DartEditor.But I ran into a couple of typos in the print version while hand-typing some of the code examples. So I urge beginners to download and use the code examples from the Packt website. And, when studying the code examples in the book (even the simplest ones), pay closer attention to the code that you can pull up in the editor.One other matter that some new Dartsians may encounter: Norton 360 antivirus software tends to throw dart.exe into quarantine on Windows machines--and that stops Dart cold. There is a fairly simple way to retrieve the file from quarantine and tell Norton 360 to let it run. Check the Dart community page on Google+ for info on that and some other approaches to avoiding the problem.Also, the book was published soon after Dart 1.0 was released, and Dart has continued to evolve a bit. (Its stable version was 1.4.3 at this time this review was written.) So there will be some slight differences in screen displays and other matters.I have read other books on how to get started with Dart, and I rate this one the best and most useful at this time..
Amazon Verified review Amazon
Juanjo Fernandez Jul 20, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
To begin with, I wish to emphasize that I am writing this review without having fully read the book, I've only checked for a few hours.This book is about Dart, a programming language created by Google in order to facilitate the creation of web applications.The first 3 chapters are about the language syntax. If you already know how to program, it will be very easy to read, especially if you know Java and JavaScript, as the syntax has seemed like a mix between these two languages.In Chapter 4 the fun begins, you'll see the importance of creating a consistent data model as the first step in creating an application.Chapters 5 and 6 discuss issues related to HTML5: DOM handling, forms, events ... frontend development.Under the pretext of create an HTML5 game, in Chapter 7 you'll put into practice what you've seen so far.Chapter 9 deepen even further in creating a data model. I was surprised that the book devotes two chapters to this subject, but I will say that the examples included are high quality.You'll know the active community that is forming around Dart through chapters 8 and 10, which talks about, among other frameworks or libraries: Polymer.dart, DQuery, Rikulo, PureMVC and Angular.dart.To complete the book, the last chapters are related to the client-server communication and data storage. Again I must emphasize the complete and useful examples included.My opinion on this book is very positive, I was surprised by the amount of information that includes about a relatively new language.Although you can find a lot of information about Dart on the official website or alternative blogs, you won't find complete and extensive articles as examples in this book.If you are interested in learning Dart quickly and reliably, I'd say you can not miss this book.
Amazon Verified review Amazon
Lidia Mar 10, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
With the release of Dart 1.0 in November 2013 we received a powerful tool for crafting robust, modern and scalable web apps. The knowledge base available for anyone wanting to get to know this Google developed language is growing, so I guess that soon we will be looking at “must-read Dart books” lists and this one has every chance of making it into each developer's canon.Who is this book for? Well, it could be a bit too much for total novices in the programming world, but otherwise I think it's really well-suited both for seasoned developers eager to try Dart, or “post-beginners” familiar with basic programming concepts and (at least having heard about) some of the latest web technologies. As authors state, because of its dual focus the book “can appeal to both web developers who want to learn a modern way of developing web applications, and to developers who seek guidance on how to use HTML5.”The core of the book are some useful Dart projects that the audience should code along, or better – code around, as authors decided to use the so-called spiral approach for explaining the vital concepts of web development with Dart. This means that on the beginning the simple solution to a given problem is presented, but later on it is being further developed (either on the basis of existing work or from scratch but making use of the just introduced concepts) in a few iterations called spirals. I am a big fan of this approach and think it is one of the best for teaching complex matters like programming – it both gives confidence about one's abilities and allows to make use of existing knowledge, while gradually expanding the student's set of skills.Learning Dart is a very comprehensive volume that covers an impressive range of Dart web development related concepts: from basics like built-in types and their methods or using classes and objects to combining Dart with HTML5 forms, developing business apps with Polymer web components, client-server communication or data-driven web apps with MongoDB and MySQL, to name just a few. Just take a look at the table of contents! It can literally take you from zero to hero in no time.tl;dr if you're looking at this review chances are you're in need of a good book that can get you up to speed with Dart programming language, look no further! This one will do it for you whether you're a ninja-rockstar-knight-commander or what have you of whatever programming language you're into or just a simple peasant trying to not feel overwhelmed by the amount of skills you have to acquire to pretend to not be a peasant anymore. And if you're somewhere in the middle, I am pretty sure Learning Dart it will do it for you too.
Amazon Verified review Amazon
Awful Scribbles Jun 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book goes through the syntax and capabilities of dart in a very straightforward manner, can't ask for more and really don't feel like I am missing much. Some general programming experience might be advantageous before diving into the book though, perhaps on the level of "Learning Python the hard way" or similar book.
Amazon Verified review Amazon
Aaron M Gifford Feb 22, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As an experienced software developer who is new to Dart, I really enjoyed this book. It begins walking through the structure and syntax of the Dart language. The description of each language feature also included the reasoning behind why particular conventions were chosen and what other languages the ideas came from. This additional information gave me a better understanding of the language and how it is designed to be used.The book covers all the major components of Dart and is a great introduction to the language and how to use it. Beyond the standard syntax and semantics, there are several nice examples of working with Polymer and HTML5 in the book. Also, there are a few different sections covering writing server code in Dart. All of the various components required to get you up and running are covered. Including a brief section on installing git and getting connected to github and walk through on installing the Dart Editor.One of the twelve chapters in the book is dedicated to a framework for automatically generating Dart code from data models. This is done using Model Concepts, Dartlero and Dartling, several open source applications created by one of the authors. There are also a few examples later in the book that use these tools as their basis. If this functionality is of interst to you, then you will really appreciate the tools and instruction the authors have provided in this area. Otherwise you might wish the space was used to cover a different topic.Near the end of the book there is a brief overview of the various web and UI frameworks available for Dart and some descriptions of each. There is also a section listing the various databases drivers that are available in Dart. With so many options available in these areas as a new user I really appreciated having a brief overview of each of these libraries and what they provide.I found myself wishing there was a whole chapter dedicated to AngularDart instead of just a short description. It is a new framework, but seems to be one of the most full featured application framework in Dart and it would have been great to explore it more. Perhaps this section can be expanded in a future edition or maybe it requires a book of its own.Dart is a new an evolving language and keeping up with the fast pace of updates is a real challenge. However, the authors did a good job of updating the content as the language has evolved. For example the elements in the sample code use Polymer ui instead of the older Dart ui. I have done other tutorials that were dated in this regard.Some minor suggestions. I might be nice to integrate some syntax highlighting in the sample code to increase the readability. Also, I did some of my reading on a mobile phone and found the sample code margins a bit too wide.If you are interested in learning about Dart I think this book is a great resource. It covers all the major language features and goes in to deeper depth on many areas that you will find in most tutorials and examples on the web. The authors also seem to be active in the Dart community and are making efforts to provide useful open source tools for Dart developers such as their model based code generation framework.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.