On Programming

A discussion of programming strategies and results

Building a User Interface With Dart

| Comments

Prerequisites

  1. A working knowledge of HTML
  2. Dart SDK

Compiling A Basic Example

First, to make sure you have Dart set up write the following into a text file and compile it

main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
  #library("main");
  #import("dart:html");
  #import("dart:json");
  #import("dart:core");

  void main()
  {
    try {
      document.body.nodes.add(new Element.html("<p>Hello World!</p>"));
    } catch (Exception ex) {
      document.window.alert(ex.toString());
    }
  }
index.html
1
2
3
4
5
6
7
  <html>
  <head>
  </head>
  <body>
  <script src="out.js"></script>
  </body>
  </html>
Compile
1
  dart2js main.dart
If everything went well dart2js should generate an out.js file. Opening index.html in your web browser should show “Hello World!”

Generating Nodes

There are two ways to generate HTML nodes for Dart.

1
  DivElement nav_div = new Element.html("<div style=\"float:right; margin:0% 5%;\"></div>");
1
  DivElement nav_div = new Element.tag("div");
You’ll notice that using the Element.html() constructor allows for you to define a lot more information in a single call. Applying the changes to style that we just need would require additional calls using the Element.tag() constructor.

It is also possible to initialize child nodes using the Element.html() constructor

1
  TableElement table = new Element.html("<table><tr><td>Row 0 Column 0</td><td>Row 0 Column 1</td></tr><tr><td>Row 1 Column 0</td><td>Row 1 Column 1</td></tr></table>");
In this example table.nodes[0] would be the first row and table.nodes[1] would be the second row.

Adding Nodes

Dart uses a tree structure to represent HTML. By default you have document.body as the root node. If we added the previous table to the document body it would have a structure like this:

dart_tree.svg

Finding Nodes

You can also locate HTML elements that already exist in your html. For example, if my HTML page was

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <html>
  <head>
  </head>
  <body>
  <link rel="stylesheet" href="style.css">
  <title>Title Here</title>
  <div id="header" class="titlebar"></div>
  <div id="container">
    <div id="center" class="column"><div id="padded_center" style="padding-left:10px; padding-right:10px;"></div></div>
    <div id="left" class="column side_nav_bar"></div>
  </div>
  <div id="footer"></div>
  <script src="out.js"></script>
  </body>
  </html>
Then I could access the header div using
out.js
1
  DivElement header = document.query("#header");
Using this, you can construct any sort of HTML page you wish.

Comments