× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Getting Started with Google Dart

See in this article a comprehensive approach on the new Google scripting language: Dart. The language allows the developer to write code that runs on both the client and the server.

Most current architecture makes use of platforms and different languages in both client and server sides, which often leads to duplicate code and increased complexity, not to mention maintenance costs and decline in staff productivity.

I am thinking about that Google created the Dart programming language, in order to facilitate the way we integrate the application as a whole.

In this article, we will see the main topics about this language: how it handles Object Orientation, syntax, responsiveness, error handling, classes, interfaces, among others.

In the end, the reader will be able to introduce the language in his projects without worrying about losing the power he had before when using JavaScript and Node.js, since it generates conversion to these and many other technologies.

In mid-2007, Google opened its first programming language, Go language or golang, starting a cycle of future releases that would trigger into powerful tools like AngularJS, GWT and App Engine. Initially, the language assumed structured and static characteristics at the expense of widespread adoption that the company has (and still do) with languages such as C and C ++.

However, over time, the need to embrace the front-end, mobile and server side universes at the same time led the company to create a new language: Google Dart.

Dart is a web-designed language, which was conceived in the GOTO conference in Denmark in October 2011, in a project funded by developers Lars Bark and Kasper Lund. Like all client side languages, Dart had to go through a battery of tests with Ecma International to verify its operation in modern browsers, so having its first specification approved and released to the community.

According to the project website "Dart has been designed to easily write development tools for modern web applications and trained for high-performance environments." Among the main features of the language, we can mention:

  • It is based on JavaScript code compilation;
  • Class based;
  • Object-oriented;
  • It’s based on the C language syntax;
  • Implements simple inheritances;
  • And it supports the main topics of OO interfaces, abstract classes, generic and optional types.

In this article, we will cover the key concepts of the new language, its syntax, major programmatic structures, its libraries and its SDK, as well as many public packages available for import into your projects (concept similar to frameworks like Grunt and React).

Environment setup

To work with Dart, the first thing to do is to download the language, along with the Dark Editor, Dart SDK and Chrommium web browser that brings a VM Dart prebuilt and available for free.

To do this, visit the official website available in the Links section and click the "Get Started". After this, you will be redirected to the platform definition page, as shown in Figure 1.

Figure 1. Download page with selected options.

Select your Operating System, then click the "Editor + SDK " option to select the full installer and the end of the items in the "Download Dart + Editor" section will appear for you to identify if your OS is 32 or 64 bits. Place the downloaded zip into the folder where you want to create your Dart projects, and unzip it there. This file is contained in the executable Dart Editor, so just run it and you will see that an IDE similar to Figure 2 appears.

Figure 2. Dart Editor Interface

Notice how the interface is very close to the Eclipse IDE, this because Google used the core of the Eclipse project (which is free and open source) to build a new development tool. This type of strategy is widely used in the market to build IDEs like Spring IDE, MyEclipse and Rational IBM tools. The Dart SDK has already been selected and should not be removed from the IDE for that language to work properly.

Dart can be used to create applications that are not attached to HTML, outside the browser. Simply integrate your environment to Node.js.

However, as most applications are made aimed at JavaScript, we will try to focus on an early example where we display a navigation menu on the browser and the user can click on it and will be redirected to two screens: one to reverse the text in an input field and another with the information of the site. This example will allow us to understand how the language handles the events of HTML pages.

Dart allows us to create various sorts of application (most with Google technology) projects as:

  • Console Application: direct running applications via command terminal, by generating .bat or equivalent files for each OS;
  • App Engine Application: applications focused on Google App Engine to run in the Google cloud;
  • Chrome App: applications or plugins for Google Chrome browser;
  • Dart Package: to create a modularized component of Dart;
  • Polymer Web Server: to host applications developed with JavaScript framework Polymer.js;
  • Web Applications: simple web applications with JavaScript, HTML and CSS support libraries.

To do this, go to "File> New Application" menu. Fill in the "Application name" with the application name and "Parent directory" with the directory where you want to save it. Let's take the name of HelloWorldDart.

Keep checkbox "Generate sample content" selected for the wizard to create a pre-established structure, and select the "Web application" option from the list that appears below. Click in "Finish". This will generate a project structure.

The lib folder contains all the Dart script files, including two ones generated for the example created by the wizard. The web folder stores all content related to the front-end: images, CSS, HTML files, favicons and other .dart files. Before running the project, let's make some changes. Open nav_menu.dart file and replace its contents with the one shown in Listing 1.

Listing 1. nav_menu.dart file

  01 // Copyright (c) 2015, DevMedia. All rights reserved. Use of this source code
  02 // is governed by a BSD-style license that can be found in the LICENSE file.
  04 library nav_menu;
  06 import 'dart:html';
  08 initNavMenu() {
  09   var navdrawerContainer = querySelector('.navdrawer-container');
  10   var appbarElement = querySelector('.app-bar');
  11   var menuBtn = querySelector('.menu');
  12   var main = querySelector('main');
  14   closeMenu(e) {
  15     document.body.classes.remove('open');
  16     appbarElement.classes.remove('open');
  17     navdrawerContainer.classes.remove('open');
  18   }
  20   toggleMenu(e) {
  21     document.body.classes.toggle('open');
  22     appbarElement.classes.toggle('open');
  23     navdrawerContainer.classes.toggle('open');
  24     navdrawerContainer.classes.add('opened');
  25   }
  27   main.onClick.listen(closeMenu);
  28   menuBtn.onClick.listen(toggleMenu);
  29   navdrawerContainer.onClick.listen((event) {
  30     if (event.target.nodeName == 'A' || event.target.nodeName == 'LI') {
  31       closeMenu(event);
  32     }
  33   });
  34 }

In line 4, we declare the library name that we are implementing (which can also be packaged and imported as an independent component in other projects). This library will be responsible for managing the navigation menu of our website. In line 6, we import the Dart HTML library. All imports must always be made using the syntax library :factory.

Lines 9 to line 12 are recovering HTML elements related to container divs, buttons and menu bar. The querySelector() function takes the element selector to retrieve and scan the page looking for it, if there is more than one, a vector is created and associated with.

The functions closeMenu() and toggleMenu() (lines 14 and 20) just try to change the CSS classes of the same elements recovered so that they change their style when a menu item is selected and deselected. The function remove(), in turn, removes the last CSS class for parameter element as toggle() tests if the class already exists, but it inserts the informed argument. The add() function (line 24) adds the reported class to the HTML element. In lines 27-29, we define the click listener of the menu components to perform page navigation functions. In Dart, always use the same attributes of events listeners "on" to tell which event should be run.

In the function listen(), Dart API receives a second function as a parameter to run whenever a click is made. Note also that Dart also allows us to create anonymous functions (line 30) instead of setting them always in separate functions.

Now open reverser.dart file that will contain the code for the reversal of the texts and add the contents of Listing 2.

Listing 2. reverser.dart file

  01 // Copyright (c) 2015, DevMedia. All rights reserved. Use of this source code
  02 // is governed by a BSD-style license that can be found in the LICENSE file.
  04 library reverser;
  06 import 'dart:html';
  08 InputElement get _inputElement => querySelector('#name');
  09 Element get _outputElement => querySelector('#out');
  11 // Example hook in the DOM and responding to input fields changes.
  12 initReverser() {
  13   // Reverses so the code starts.
  14   _reverse();
  16   // Reverses there each key release.
  17   _inputElement.onKeyUp.listen((_) => _reverse());
  18 }
  20 _reverse() {
  21   _outputElement.text = _inputElement.value.split('').reversed.join();
  22 }

In line 4, we again set the library name, and in line 6, we import the HTML lib. In line 8, we retrieve the input field name to be typed and added to an InputElement object of Dart API. In line 9, we retrieve the element related to the output field (Dart offers this and other new HTML tags) to print the reverse text. In line 20 we call function _reverse() that simply accesses the value of the input field, breaking it into a vector of chars (split) and draws reversed property that will be responsible for reversing the vector positions. In the end, we call join() function that unites the vector into a string again and add to the text property (as it is an output field, do not use the "value" of input, but "text") of the element .

Finally, on line 17 we implemented the onKeyUp event for when the user types something in the field and associate the _reverse() function to the same. Now we need to edit the file main.dart representing the initial scope of the framework implementation, that is, it will always carry the other dart files from it. To this, add the contents of Listing 3 to it.

Listing 3. main.dart file

  01 // Copyright (c) 2015, DevMedia. All rights reserved. Use of this source code
  02 // is governed by a BSD-style license that can be found in the LICENSE file.
  04 import 'dart:html';
  06 import 'package:HelloWorldDart/nav_menu.dart';
  07 import 'package:HelloWorldDart/reverser.dart';
  08 import 'package:route_hierarchical/client.dart';
  10 void main() {
  11   initNavMenu();
  12   initReverser();
  14   // Webapps need routing to hear the changes in the URL. 
  15   var router = new Router();
  16   router.root
  17     ..addRoute(name: 'about', path: '/about', enter: showAbout)
  18     ..addRoute(name: 'home', defaultRoute: true, path: '/', enter: showHome);
  19   router.listen();
  20 }
  22 void showAbout(RouteEvent e) {
  23   // Extremely simple and non-scalable way to show different views.
  24   querySelector('#home').style.display = 'none';
  25   querySelector('#about').style.display = '';
  26 }
  28 void showHome(RouteEvent e) {
  29   querySelector('#home').style.display = '';
  30   querySelector('#about').style.display = 'none';
  31 }

In lines 6-8, we see the import of the two Dart script files that we created before, and a new "client.dart". This file will be inherited from the API to implement the routing of pages, ie, to deal with the URL changes according to the actions defined for each page. In line 15, we create a new object Router, which is responsible for defining the possible routes for the application as a whole. The addRoute() method takes some parameters, namely:

  • name: name of the route.
  • path: relative URL of the internal path of the route.
  • enter: get the function to call when this route is accessed.
  • defaultroute (optional): boolean to determine if the current route is the default.

The showHome and showAbout methods are responsible for displaying and hiding the page content divs. These should be increased as the pages increase in the application. Finally, we will edit the HTML page index.html. It is a bit long, so let's split into two parts: header/navigation (Listing 4), and conversion/about pages.

Listing 4. Head content and div navigation of index.html page

  01 <!DOCTYPE html>
  03 <html>
  04 <head>
  05   <meta charset="utf-8">
  06   <meta http-equiv="X-UA-Compatible" content="IE=edge">
  07   <meta name="viewport" content="width=device-width, initial-scale=1.0">
  08   <meta name="scaffolded-by" content="https://github.com/google/stagehand">
  09   <title>HelloWorldDart</title>
  11   <!-- Add to the homescreen for Chrome on Android -->
  12   <meta name="mobile-web-app-capable" content="yes">
  13   <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">
  15   <!-- Add to homescreen by Safari in iOS -->
  16   <meta name="apple-mobile-web-app-capable" content="yes">
  17   <meta name="apple-mobile-web-app-status-bar-style" content="black">
  18   <meta name="apple-mobile-web-app-title" content="Web Starter Kit">
  19   <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
  21   <!-- Tile icon for Win8 (144x144 + tile color) -->
  22   <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
  23   <meta name="msapplication-TileColor" content="#3372DF">
  25   <!-- TODO: Replace the two stylesheet references to use Sass
  26     (and make the sass transformer in pubspec.yaml file. -->
  27   <link rel="stylesheet" href="styles/main_gen.css">
  28   <!-- link rel="stylesheet" href="styles/main.css" -->
  29 </head>
  31 <body>
  32   <!-- Example content. -->
  34   <header class="app-bar promote-layer">
  35     <div class="app-bar-container">
  36       <button class="menu"><img src="images/hamburger.svg" alt="Menu"></button>
  37       <h1 class="logo">Reverser Words</h1>
  38       <section class="app-bar-actions">
  39       <!-- Put App Bar Buttons Here -->
  40       <!-- e.g <button><i class="icon icon-star"></i></button> -->
  41       </section>
  42     </div>
  43   </header>
  45   <nav class="navdrawer-container promote-layer">
  46     <h4>Navigation</h4>
  47     <ul>
  48       <li><a href="/">Home</a></li>
  49       <li><a href="/about">About</a></li>
  50     </ul>
  51   </nav>

Most of this list comprises style import tags and meta tags, as well as HTML divs structure to contain the navigation menu. The meta tags of lines 12 and 13 serve to create an application shortcut on Android devices. Likewise, the lines shown in 16 to 18 do the same for iOS. In line 22, we have a representation of this code for devices running Windows 8/Windows Phone. In line 25, we have the contents of the style tag needed to instill Sass pages if desired. The rest of the implementation brings only divs and links for navigation. The structure was made based on the CSS provided by Dart in the newly created project. The second part of the page may be found in Listing 5 and must be added immediately after the end of the previous one.

Listing 5. Contents of conversion/about pages.

  01  <main>
  03    <div id="home">
  04      <p>
  05        Name:<br>
  06        <input type="text" id="name" placeholder="Enter your name...">
  07      </p>
  09      <p>
  10        Reversed:<br>
  11        <output id="out"></output>
  12      </p>
  13    </div>
  15    <div id="about" style="display:none">
  16      <p>
  17        This is a basic HTML demo application built with Dart.
  18        For developers who do not want or can not use polymer.dart,
  19        this is an optional starting point.
  20      </p>
  21    </div>
  23    <div class="sass-hidden">
  24      <p>
  25        Note: To use Sass with this application,
  26        change the style sheet references in the &lt;head&gt;
  27        and uncomment transformer sass in pubspec.yaml file.
  28      </p>
  29    </div>
  30  </main>
  32  <script type="application/dart" src="main.dart"></script>
  33  <script data-pub-inline src="packages/browser/dart.js"></script>
  34 </body>
  35 </html>

As a best practice implementation on the front end, we are importing the Dart script files only at the end, so we gain in performance because the page is already loaded when we get these files. Note that the script tag type attribute (commonly filled with the value "text/javascript") should be filled with "application/dart" always. Once src points to the main.dart file. The second script tag (line 33) loads the Dart API page. Note also that the second div should come hidden (display: none) so we can display it only when selected in the menu. See how easy it is to instill browsing Dart: just create divs and hide them, letting the API takes care of redirects to where you send. After this, save all files and click the Run button at the top of the IDE or select the Ctrl + R.

Note that the Editor will open a Google Chrome internal window. You do not need to have the browser installed, as it brings an internal instance of the same in the installation package. This approach is used by Google to avoid doing tests on internal browsers to IDEs (such as Eclipse, for example), allowing more real and automated testing. Communication with testing frameworks like Selenium is easy to be made in this version of Chromium. Note that the URL bar of the browser, inside it, has opened the application at http://localhost: 8080. This is the default URL of the framework, because it makes use of Node.js to build and run JavaScript on the server. By chance if you are unable to run or show any port error in use, make sure it is not running any tool that uses port 8080 as the Java Tomcat and JBoss servers, for example.

Still on the URL, see that on the screen About we have the URL with its respective termination. This is because we define that the action is to display the div with the name property of value about. Dart also generates responsive content automatically. Therefore, if we run the same screen on a smartphone or tablet device, it will result in a smaller screen.

Modularity and Namespace

The concept of modularity is based on the division into smaller independent components. In addition, each module needs to have a unique responsibility and provide structures to connect to it. For example, if we have a hospital system and want to divide it into modules that can be coupled to other third-party systems, we would have a module for the warehouse, the other for the control of appointments, plus one for the registration exams, and so on.

This type of feature is widely used by client software in need of some components while others in the same business do not. In the world of programming, this division takes the name of "decomposition". For each part of the system is decomposed, it must go through a cycle of actions: create, change, test, use and separate replacement. The modularity of the Dart is made through the package, and class libraries.

The library exposes the functionality as a set of interfaces and hides the implementation of the rest of the world. As a concept, it is very similar to the separation of responsibilities we have in Object Oriented Programming, for example. As a result, the user experiences less concentrated code and easier time to keep the same, since the changes are concentrated now, but a component only. Furthermore, the library concept shall not only encompass server side APIs, but front-end frameworks.

The package is a simple directory containing a file called pubspec.yaml and includes in itself an x amount of libraries and resources. This file contains important information about the package as their authors, and their dependencies on other packages. Let's see in Listing 6 the contents of this file created in our example HelloWorld. Note that it works as a kind of Google Doc, but specifically for Dart; Moreover, these are just basic fields, you can find a list of other options in the official language site (see Links section).

This file is required for your operating system to recognize the kind of technology that will operate there. Before being used, a package should always be published in a "package management system", which is available as an online resource called pub (see in the Links section the URL of the official Dart pub). Regarding the recovery of these packages in the pub, a utilitarian application of the same name can be used for such. This uses information about the pubspec.yaml dependencies to retrieve all packages needed the following locations: the newly updated packages in the Dart pub website; Git Repository; the directory on the local filesystem.

The classes can be represented using common functions or inheritance prototypes.

Listing 6. Structure of default project directories.

  01 name: 'HelloWorldDart'
  02 version: 0.0.1
  03 description: >
  04   The mobile-friendly web app with routing, responsive CSS, and (optional) Sass
  05   support.
  06 #author: <your name> <email@example.com>
  07 #homepage: https://www.example.com
  08 environment:
  09   sdk: '>=1.0.0 <2.0.0'
  10 dependencies:
  11   browser: '>=0.10.0 <0.11.0'
  12   sass: '>=0.4.0 <0.5.0'
  13   script_inliner: '>=1.0.0 <2.0.0'
  14   route_hierarchical: '>=0.5.0 <0.7.0'
  15 transformers:
  16 - script_inliner
  17 #- sass:
  18 #    style: compressed

Since namespaces are containers for all members of a library. A namespace is defined by the library name. That is, if a library is implicitly named so it has an empty namespace. This often results in conflicts when trying to import libraries with the same namespaces. Such conflicts can be avoided with a fixed clause (as) and a prefix name. See Listing 7. In it, we have an example of implicitly named library in which all dart resources: HTML are available through the scope of our library with the dom prefix. >

Listing 7. Example of a implicitly named library.

  01 /**
  02 * Library named implicitly.
  03 * The lib dart: core is automatically imported.
  04 */
  05 import 'dart:html' as dom;
  06 /**
  07 * Recupera [Elemento] por [id].
  08 */
  09 dom.Element getById(String id) => dom.querySelector('#$id');

Obviously, all markings and selectors will only be recognized in a Dart environment. The browser cannot interpret this notation. Note that in line 5, we make use of the clause "as" to import the resource (HTML library Dart) dynamically.

In line 9, we make the recovery of the id element by its id HTML attribute. This is quite similar to how jQuery makes the selection of its attributes, for example. However, when compiled to JavaScript, all this code loses information from libraries and we have a very different file being generated. Dart implements the concept of encapsulation through privacy. Each member or identifier of a library has one of the two access levels: public or private. Private members are visible only within the library in which they are declared. On the other hand, members with a public access are visible everywhere. The difference between them is the underscore (_) prefix, as shown in Listing 8 code.

Listing 8. Example of encapsulation in Dart.

  01 // Library Animation.
  02 library animation;
  03 // Class publicly available anywhere.
  04 class Animation {
  05 // ...
  06 }
  07 // Class visible just inside the library.
  08 class _AnimationLibrary {
  09 // ...
  10 }
  11 // Variable publicly available anywhere.
  12 var animationSpeed;

The code shows an animation library with two classes and one variable. Class Animation and animationSpeed variable are public and therefore visible from outside the library. The _AnimationLibrary class is private and can only be used into the library. Public access can be controlled with the extensions show and hide in the import declaration. Use the following extension show with a specific class, which will be available within the library that is imported:

import 'animation.dart' the animation show Animation;
   main () {new animation.Animation (); }

The prefix animation in the import statement defines the namespace to import the animation.dart library. All members of animation.dart library are available in the global namespace prefix through this. Since the extension hide specified in the class will make that same inaccessible from within the library to which it was imported. This is interesting when we need a class to be only accessed from within the API itself, as security classes, databases connection, etc .:

import 'animation.dart' as animation hide Animation;
  main() { var speed = animation.animationSpeed; }

Functions and Closures

In Dart you can create functions via variable, that is, create a reference to a function and assign to a variable, as can be seen in Listing 9.

Listing 9. Function example with association of functions to variables.

  01 library function_var;
  02     // Return sum of [a] and [b]
  03     sum(a, b) {
  04           return a + b;
  05     }
  06     // Operation
  07     var operation;
  08     void main() {
  09           // Assigns the reference to the [sum]
  10           operation = sum;
  11           // Run operation
  12           var result = operation(2, 1);
  13           print("Result is ${result}");
  14     }");
  15 }

The result is 3. Note that we create a simple function of the sum of two values and add the function to a variable (operation, line 10) calling it instead of the function sum(). In line 13, we print the sum. See the prints in the JavaScript console are made via print() method and the values to concatenate by operator ${}. Dart is still dealing with the passage functions as arguments to other functions; callback functions as a result of other (return) function, and can save data structures, such as vectors, for example.

The function can be created globally or within another function. A function that can be referenced with an access to the variables in your lexical scope is called closure. Let's look at the code in Listing 10.

Listing 10. Example of closure in Dart.

  01 library function_closure;
  03 // Function returns a closure.
  04 calculate(base) {
  05     // Counter
  06     var cont = 1;
  07     // Internal function - closure
  08     return () => print("Value is ${base + cont++}");
  09 }
  10 void main() {
  11     // The external function returns the internal
  12     var f = calculate(2);
  13     // Now we call closure
  14     f();
  15     f();
  16 }

The structure to create a closure is the same for the common functions. The difference is that the closure is created and returned from within an existing function. It works as an anonymous function that can be easily created without the need of any apparatus keywords to form the common functions. Note that in line 8, after creating the counter variable, we are associating the act of printing the sum and counter to an empty() function. The operator => is to make this association, very common in structures such as lambdas. After that, whenever we wanted to call this closure just return to a variable and make the call: f() (lines 14 and 15). In this example, the results will be 3 and 4, respectively.


Official page of download Dart.


Package Repository page Dart.


Fabrí­cio Galdino is a software expert and has worked with IT analysis and business development for more than five years. It has extensive experience with testing, back and front-end technologies.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login