Dart for Java developers: a simple web app

In the previous installment of my small series of posts about Dart for Java developers we have put together the pieces we crafted so far. We saw a small console application which used both model and converter libraries. As a next step we will be building a small web application. The following screenshot shows the running program.

a temperature converter web app

The corresponding html file is fairly simple. If you take a look at the body you find three tags: h1, form and p. The latter one will receive the computed temperature. The headline is merely decorative. The form comprises a text input field for the input temperature, two fieldsets which contain radio buttons for the input and output temperature units, and a button. There is no css to make the ui a little more fancy. Relating pull requests would be greatly appreciated.

So far, so easy. But how do we connect the html file to a Dart program, and how does this look like? The head contains two script references:

<script defer type="application/dart" src="main3.dart"></script>
<script defer src="packages/browser/dart.js"></script>

The latter one bootstraps the Dart runtime, whereas main3.dart (yes, that name is not extraordinarily desriptive ;-)) refers to the program. Let's take a look at it. There is a toplevel main() function, which connects the code to ui elements through querySelector(). To be able to use this function, we must import the dart:html package. Have you spotted the two calls to listen()? One is used to receive button clicks, while the other one will give us events when a key icharacter is entered. We use this to disable the button if the input field is empty. The remaining code is straight forward. We instantiate a model class, set it up, and have it calculate the output temperature.

Isn’t that easy?

No comments:

Post a Comment