2013-06-16_11-12-28_thumb.png

Getting Started With Google’s Dart Language

I was a little skeptical of the Dart language when Google first announced it.

When I looked at the syntax of the language I thought that it didn’t really seem to offer anything new.

Why create another language that is not very different than what we already have?

How is this actually much better than JavaScript?

But after having worked with Dart now for quite awhile and producing a Pluralsight course on Dart, I’ve completely changed my mind.

The Dart language is awesome!

What makes the Dart language so awesome is all the little subtleties the language designers added to the language, not any major new concepts or ideas.

When I started writing Dart code it felt exactly right.  It felt like all the little annoyances that I had with languages like C#, Java and JavaScript were removed by the Dart language.

In fact, the real beauty of Dart is that if you already know C# or Java and JavaScript, you’ll probably be able to learn enough about the Dart language to be productive in Dart in less than an hour.

Before I show you just how easy it is to get started, let me briefly tell you what the Dart language is:

  • Object oriented.  Everything is an object including primitives and nulls
  • Optionally typed.  You can add type annotations which static checking tools can use to help you find errors in your code, but you don’t have to use them.
  • Interpreted.  Dart is run in a VM, but it is not compiled first.  Round-trip time for making changes is very short.
  • Compatible with JavaScript.  You can compile your Dart code to JavaScript and run Dart applications in any modern browser.
  • FAST!  Dart is very fast, much faster than JavaScript in just about every test.

Some cool language features that I like about the Dart language:

  • Mixins.  Instead of using inheritance, you can use a mixin to add functionality to a class without directly inheriting from another class.
  • Isolates.  Instead of threads, the Dart language uses isolates for concurrency.  Isolates can’t actually share any memory, they pass information though messages.  It is very hard to shoot yourself in the foot.
  • Simplified built-in types.  Numbers can be either int or double, and you can just use num, if you don’t care.  Lists and maps can be declared as literals.  An array is just a special case of a list.
  • Functions are first-class objects.  You can pass them around just like any other object.  There is even a lambda-like short-hand for creating a one-liner function.
  • Top level functions and variables.  Don’t want to put a function or variable in a class?  Good, you don’t have to.  In the Dart language, you can declare them anywhere you want.
  • Simplified classes.  There is short-hand for declaring constructors that assign parameters to class members.  Class members don’t have protected, private, public.  Member variables are automatically properties.
  • String interpolation.  No more string format methods, just use the $variableName in a string to have its value expanded.

Getting setup with the Dart language

Ready to get running in 5 minutes?

Ok, read on.

Step 1: Go to http://dartlang.org and click “Get started.”

2013 06 16 11 12 28 thumb Getting Started With Google’s Dart Language

Step 2: Download Dart (64-bit or 32-bit.)  Unzip the file and copy the “dart” folder to where you want Dart installed.

This folder will contain the Dart Editor, the Dart SDK and the Chromium web browser which has a built-in Dart VM.

Step 3: Run DartEditor.exe

Dart Editor 2013 06 16 11 18 01 thumb Getting Started With Google’s Dart Language

That is it, now you are ready to rock some Dart code!

Creating your first Dart language App

The Dart language can actually be used outside of a browser, just like you can use JavaScript with Node.js.  But, most developers will probably want to use Dart the same way we use JavaScript in a web application today.

I’m going to walk you through a real simple example that will show you how to create a basic Dart application that is able to respond to a button click and manipulate some DOM data.  For more advanced examples, you can check out my recently released Pluralsight course on Creating Web Applications with Dart. (I will plug this one more time before this post is over… wait for it…)

Step 1:

Go to File –> New Application.

Fill in your application name.  I’ll call mine HelloWorldDartWeb.

Leave “Generate sample content” checked.

Select “Web application.”

2013 06 16 11 24 03 thumb Getting Started With Google’s Dart Language

Step 2:

Open the helloworlddartweb.html file and clear out everything in the body element except for the two script tags at the bottom.

The first script tag imports our actual Dart file, just like you would use to add JavaScript to a page.

The second script adds Dart support to the browser.

Step 3:

Add the following HTML to the body tag in the helloworlddartweb.html file:

[sourcecode language=”html” padlinenumbers=”true”]

[/sourcecode]

This will just create a button and a div.  We are going to add some Dart code to respond to a button click and populate the div with some text.

Step 4:

Open the helloworlddartweb.dart file and clear out everything in main() and delete the reverseText function.

Notice that there are only two things we really will need in our .dart file.  Just an import ‘dart:html’, to import that html library for Dart, and the main function, which executes as soon the DOM content is loaded on the page.

Step 5:

Edit the helloworldweb.dart file to make it look like this:

[sourcecode language=”text”] import ‘dart:html';

void main() {
var button = query(“#theButton”);
button.onClick.listen(addResult);
}

void addResult(Event e) {
var resultDiv = query(“#resultDiv”);
resultDiv.text = “You clicked the button”;
}
[/sourcecode]

This code simply gets the button using a CSS selector.  It uses the query function to do this.

Then we register the addResult function as an event handler for the onClick event for the button.

In the addResult function, we simply query for the resultDiv and change its text.

After you run this example, you should see a result like this:

HelloWorldDartWeb   Chromium 2013 06 16 11 47 56 thumb Getting Started With Google’s Dart Language

Step 6:

Now change the Dart code to look like this:

[sourcecode language=”text”] import ‘dart:html';

void main() {
query(“#theButton”)
.onClick.listen(
(e) => query(“#resultDiv”).text = “You clicked the button!”
);
}
[/sourcecode]

Try running the code again and you should see it works exactly as before.  Here we just shortened the code to a single line by using the short-hand function syntax.

Going further with the Dart language

So, that is just the basics of Dart.  I wanted to show you how to get started really quickly, but I am sure there is more you will want to learn about Dart.

We can of course do much more with Dart, especially when building web applications.  There is a Dart Web UI library which can be used to do templating and data binding so we can simplify our Dart code even further.

The language itself is pretty simple.  Most C# and Java developers, as well as JavaScript developers, should be able to read and understand Dart code without any assistance.  But here is a link to an overview of the language.

If you are looking for a more in-depth coverage of the Dart language and want to see how to build a real application with Dart, check out my Introduction To Building Web Applications With Dart course on Pluralsight, where I go over the entire language and guide you through building a real application, as well as cover some of the more advanced features like mixins and isolates.

Also, I could only find two books on the Dart Language.

I don’t know if Dart will end up replacing JavaScript, but I do think Dart has the potential.  It really is an awesome language that is fun to develop in.

That is strong praise coming from me, since I really tend to dislike dynamic languages.  The creators of Dart have really done a good job of creating a language that is succinct, fast, easy to work with and has the best advantages of strongly typed languages with all the flexibility of dynamic languages like JavaScript.

Get Up and CODE and YouTube Videos

For those of you who frequent my blog and are looking for my latest Get Up and CODE podcast episode and YouTube video for the week, I have a bit of an announcement.

I am going to start posting these blog posts every Monday.

The YouTube videos will be going up every Wednesday.

The Get Up and CODE podcast will be coming on every Friday.

When my new website design is done, you’ll be able to find the latest episodes of each on the side bar, so I’ll stop including them in each weekly post.

But here is last week Get Up and CODE, where Iris and I talk about basic weight training.

Get Up And Code 006: Basic Weight Training

  • Fred G. Vader

    Hi John, another Dart book to add to your list is “Dart for Hipsters”. The good thing about this particular book is that the author periodically releases updates to account for the changes in Dart since it is still pre-1.0.

    http://pragprog.com/book/csdart/dart-for-hipsters

    • jsonmez

      Nice, thanks! I’ll have to check that one out.

  • Rolando Mauricio Carias

    What would you say is the difference between Dart and TypeScript? It seems to me that TypeScript is more light-wight and portable (no need for a VM use whatever the browsers already give us for free).

    • jsonmez

      Great question.
      In my opinion it comes down to 2 main things.
      1. Dart is a independent language that can be compiled down to JavaScript, but doesn’t have to. TypeScript is a superset of JavaScript, which greatly restricts it’s development and usage. As a good example of why, in general, I don’t like superset languages, take a look at Objective-C, a superset of C.
      2. Dart is fast! Very very fast. Like 8x the speed of the fastest JavaScript engine. Dart isn’t even optimized yet. In my mind, this is huge!

      • Rolando Mauricio Carias

        I agree with #1 except for the fact that in order to make it portable, you have to explicitly compile to JS. As for #2, I would imagine the reason why it’s fast it’s because the VM is tightly coupled to Chrome. It kind of reminds me of Java Applets which require a VM. However, I would bet that as the web paradigms progress and with ECMA Script 5, the engines for JS will be also 8X faster natively.
        What would you save are the best use-cases for wanting to use Dart for an Enterprise/Commercial application?
        BTW, I enjoy your workout/career tips. Keep it up!

        • jsonmez

          I agree with what you said in the current web environment, but I believe Google has big plans with Dart and Blink. Think about what happens when the Dart VM is baked into Blink and other browser vendors quit using the dead webkit branch and move over to Blink. Suddenly, a majority of browsers support Dart VM out of the box. If this happens, the speed of Dart will make it a competitive advantage to use, and there would be no sacrifice in portability, because no Dart VM browsers could just use the JavaScript translated version.
          So, I think that the reason someone would want to user Dart today is because at the very least it makes it easier to write an application that is heavy on client side scripting, which will work even without a Dart VM. The Dart language is a big improvement over JavaScript, IMO.

          Thanks for the encouragement on the podcast and
          YouTube videos. I am enjoying doing these! :)

      • Fred G. Vader

        to elaborate on John’s superset point, TypeScript s just syntactic sugar for JavaScript that provides a more traditional OO approach to JavaScript that most .Net/Java guys are accustomed to and thats it.

        Dart on the other hand not only brings OO features to the table but as the Dart team likes to say it comes with “batteries included” i.e. it has libraries that support html, IO, isolates (i.e. threading), templating, data-binding, web components, etc etc.

        I see Dart as the new “.Net” of the web whereas TypeScript is just syntactic sugared version of JavaScript.

    • kaisellgren

      I think two biggest differences are:

      1) Dart is not just syntax upgrade from JS unlike TypeScript.
      2) Dart works great on the server (maybe it’s possible to run TS too but I doubt it was meant for that..)

  • Pingback: Июньская лента: лучшее за месяц()

  • Pingback: Getting Started With Google’s Dart Langua...()

  • Pingback: Getting Started With Google’s Dart Langua...()

  • suza

    I want to learn the web development languages. Now I came to know the dart language. If I learn Dart which other language I should learn to be a web developer. Please advice me.

    • sethladd

      If you learn Dart, you should also learn JavaScript, HTML, and CSS. Dart is a good place to start because of its bundled libraries and editor.

      • Krishnamani M

        i am also new to development. i know html , css but not much knowlwedge in javascript. Is it must to know javascript to learn google dart. pls advice.

  • Pingback: Июньская лента: лучшее за месяц (2013)()