The original address: www.thepolyglotdeveloper.com/2019/04/bui…

Original author: disqus.com/by/ewaldhor…

Release time: April 24, 2019

Dart is a programming language developed by Google and made popular by Flutter, its mobile development framework for cross-platform application development.

The Dart language is a general-purpose language built for more than just mobile development, and in this short tutorial, I’ll show you how to use Dart to build a basic Web application.

What you need to know

I’m going to assume that you are comfortable with Web application development, that you understand DOM, HTML, CSS, and so on, and that you have some basic JavaScript background. If you’re new to Web development, I recommend starting with the Dart documentation, which explains concepts like DOM in detail.

If you’re comfortable writing HTML, CSS, and very basic JavaScript, you’ll easily get through this tutorial and learn some Dart skills along the way. For the curious, the Dart language tour is a great way to quickly learn enough of the Dart language to start using it, especially if you have previous programming experience in other languages such as C#, Java, JavaScript or Python.

As we work through this tutorial, I’ll introduce some Dart programming concepts and point you to the documentation if you need it. You don’t need to know the Dart language to get started with this tutorial.

Get Web development for Dart installation and configuration.

Dart provides an easy-to-use installation guide for each supported platform, which you can find on the Dart language website. Windows, Linux, and Mac all have detailed instructions. In this tutorial, you should install the Dart SDK.

The Dart SDK includes a number of useful command-line tools.

  • Dart-dart VIRTUAL Machine (VM)
  • Dartdoc – an API document generator
  • Dart 2JS – a Dart to Javascript compiler that allows you to implement web goals with Dart.
  • Dartfmt-dart code formatter.
  • Dart Analyzer – Static code analyzer for Dart.
  • Pub-dart Software package manager
  • Dartdevc – a very fast Dart compiler, very useful for web development.

Once you have Dart installed, open a command prompt and execute the following command based on your platform’s specifications.

dart --version
Copy the code

You should see something like this.

Dart VM version: 2.2.0 (Tue Feb 26 15:04:32 2019 +0100) on "macos_x64"
Copy the code

Now that Dart is installed, let’s set up the CLI tool we’ll be using. Dart package manager, Pub, makes it easy to add and manage Dart packages. We will use pub to install the command-line interface tool.

First, we install the Web development tools.

pub global activate webdev
Copy the code

You can test whether Webdev is working by running the webdev command.

webdev
Copy the code

Then we install Stagehand, a Dart scaffolding tool.

pub global activate stagehand
Copy the code

Ensure that Stagehand is working properly by running the following command.

stagehand
Copy the code

Our first website development project

Let’s create a simple Web development project using the Stagehand scaffolding tool. The advantage of using this tool is that it will do a lot of the heavy lifting for us. Setting up a new project in Dart requires the creation of predetermined folders, and StageHand makes this a breeze.

For our first project, we will create a very simple web application. In order for Stagehand to create scaffolding for our project, we must first create a new folder to hold the project. I will use DartWeb as my project folder. You are welcome to create any empty folder you want and navigate to it.

Once the folder is created and you have navigated through it, run this command.

stagehand web-simple
Copy the code

The project scaffolding will be created and you will be instructed to run pub GET to update the project’s dependencies. run

pub get
Copy the code

The project’s dependencies will be resolved and updated, allowing us to call the WebDev tool to see how our generated application is doing.

Run the following command and point the browser to http://localhost:8080 once it shows Serving ‘web’ on http://localhost:8080.

webdev serve
Copy the code

You should see something like this.

Make some changes

One thing you’ll quickly notice when using Dart is how quickly you can change. Let’s take a look at this and add a little style to our page.

First, open the style.css file in the Web folder. It should have the following content.

@import url(https://fonts.googleapis.com/css?family=Roboto);

html.body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    font-family: 'Roboto', sans-serif;
}

#output {
    padding: 20px;
    text-align: center;
}
Copy the code

This is created automatically for us by the Stagehand tool when we instruct it to create a simple web project for us. Update the style. CSS file to add the following to #output.

font-weight: bold;
background.#BABBAA; #BABBAA #BABBAA;
Copy the code

It should look something like this

#output {
    padding: 20px;
    text-align: center;
    font-weight: bold;
    background: #BABBAA;
}
Copy the code

Save the file, go to your browser, and refresh the page. You should see something like this.

Updates CSS

The Dart tool, WebDev, monitors the files in our project and automatically triggers rebuilding and redeployment when you save changes. This saves you a lot of time and effort and makes the developer experience smoother. This is expected, but, for the most part, it works very well. Most of the time, all you need to do is refresh your browser to see your changes.

If you look at the console output, you’ll see something like this every time you save changes to the file.

Update the HTML

We’ve seen how easy it is to update CSS, but what about HTML? First, let’s look at the default HTML document that Stagehand created for us.

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <meta name="scaffolded-by" content="https://github.com/google/stagehand">
        <title>dartweb</title>
        <link rel="stylesheet" href="styles.css">
        <link rel="icon" href="favicon.ico">
        <script defer src="main.dart.js"></script>
    </head>
    <body>
        <div id="output"></div>
    </body>
</html>
Copy the code

That seems pretty standard, right? The only thing that looks a bit funny is the SRC attribute of the

Since this is just standard HTML, we can modify it. Add the following code to the body of the page, around the Outputdiv.

<header style="text-align: center;">
    <h1>A simple Dart web project</h1>
</header>

<div id="output"></div>

<footer>
    <p>For more information about Dart, please visit the <a href="https://www.dartlang.org/" target="_blank">offical website</a>.</p>
</footer>
Copy the code

Save the file and refresh the browser. It should look something like this.

Writing HTML for the Dart Website project does not require any new skills or knowledge. You can use standard HTML tags, inline CSS, and external style sheets.

Now, more on Dart bits in JavaScript files

So where does Dart fit into all this? We see that JavaScript in HTML includes a DART, which is very unusual. There is also a main.dart file in our Web folder that looks like this.

import 'dart:html';

void main() {
    querySelector('#output').text = 'Your Dart app is running.';
}
Copy the code

If you look at the sentence ‘Your Dart app is running.’ you’ll see that’s what appears on the HMTL page in our browser. The code selects the # Output tag with the querySelector Dart method and changes the text to our message. So how does this work?

Dart compiles our source code into JavaScript and runs it in a browser. This means you can write code in Dart that executes in a browser without having to know JavaScript.

We can make some changes to the Dart code, save the file, and refresh the browser. See if you can change the main.dart code to Hello, dart!

Your main.dart file should now look like this.

import 'dart:html';

void main() {
    querySelector('#output').text = 'Hello, Dart! ';
}
Copy the code

Be prepared to do more

Before we start doing all sorts of things with Dart, let’s add some more content to the HTML page. You can use any image you like, but try to keep the identifiers and style names consistent, otherwise the code may not work.

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <meta name="scaffolded-by" content="https://github.com/google/stagehand">
        <title>dartweb</title>
        <link rel="stylesheet" href="styles.css">
        <link rel="icon" href="favicon.ico">
        <script defer src="main.dart.js"></script>
    </head>
    <body>
        <header style="text-align: center;">
            <h1>A simple Dart web project</h1>
        </header>
        <div id="output"></div>
        <div>
            <img src="tears_image.jpg" id="tears">
        </div>
        <div class="dogs">
            <ul>
                <li>roofus</li>
                <li>sally</li>
                <li>puddles</li>
                <li>abe</li>
                <li>nox</li>
                <li>charlie</li>
            </ul>
        </div>
        <footer>
            <p>For more information about Dart, please visit the <a href="https://www.dartlang.org/" target="_blank">offical website</a>.</p>
        </footer>
    </body>
</html>
Copy the code

The picture I used.

Save your changes and refresh your browser, and you should see something like this.

Fix image alignment with Dart

For example, for some reason you need to use Dart to correct the alignment of an image. While it might be more efficient to use static CSS, it gives us an opportunity to interact with the DOM using Dart.

We need to select the image, find its div, and change one of its attributes. Then we also want to set some style properties on the image itself.

  1. Create a new method in the main.dart file.
void alignImageProperly() {
    querySelector('#tears')
        .parent.style.setProperty("width"."100%")
        .style.setProperty("display"."block")
        .style.setProperty("margin-right"."auto")
        .style.setProperty("margin-left"."auto")。
}
Copy the code
  1. Make sure this method is inmainIs called in.
void main() {
    querySelector('#output').text = 'Hello, Dart! ';
    alignImageProperly().text = 'Hello, Dart!
}
Copy the code
  1. Save and refresh!

Our expected output.

So what happened? Let’s look at the code in more detail. To make things easier, I’ll add line numbers.

1. void alignImageProperly() {
2.     querySelector('#tears')
3          ..parent.style.setProperty("width"."100%")
4.         ..style.setProperty("display"."block")
5.         ..style.setProperty("margin-right"."auto")
6.         ..style.setProperty("margin-left"."auto");
7. }
Copy the code
  1. Let’s declare our new function calledalignImageProperly, the return type isvoid.
  2. Using the Dart methodquerySelector, we get an ID oftearsA reference to a picture.
  3. Once we have this reference, we access our image’sparentAnd willwidthProperty set to100%. Please note that the DartCascade symbolUse of functionality. This feature allows us to runquerySelectorAnd retains a reference to the returned element. With this cascade operator, we can call a function on this reference without having to re-run the selector or create a temporary variable.
  4. Now let’s set the image itselfdisplayStyle properties.
  5. Set on the imagemargin-right.
  6. Set on the imagemargin-left.
  7. Close our function body.

Add a title to our list of names

Dart not only lets you modify the style of an element, but it also makes it easy to add new elements to the DOM. Let’s add a caption to the list of names under the image.

Dart create a new function in your main.dart file.

addHeader() {
    var heading = HeadingElement.h3();
    heading.text = "Animal Names";
    querySelector('.dogs').children.insert(0, heading);
}
Copy the code

Make sure it is called in main.

void main() {
    querySelector('#output').text = 'Hello, Dart! ';
    alignImageProperly().text = 'Hello, Dart! addHeader().text = 'Hello, Dart'; alignImageProperly(); addHeader();
}
Copy the code

Save and refresh, you should see something like this.

So what happens in those three lines of code that make up our addHeader function? Well, we use Dart’s H3 named constructor function to create a new HeadingElement and save a reference in the heading. Next, we modify the text of the heading element, and finally, we insert it as the first child of the div, with class Dogs.

These names need some attention

Now that we’ve added a title to the list, we can look at modifying the list itself. Names should start with a capital letter, and the list doesn’t look right.

Let’s fix the alignment, which is not so much good Web development practice as an excuse to add a CSS element to our stylesheet.

Create a function called addStyleElement as follows.

var styleElement = new StyleElement();
document. Head. Append (styleElement). CssStyleSheet sheet = styleElement.sheet;final rule = '.dogs { width: 150px; padding: 20px; margin-left: auto; margin-right: auto; display: block; } ';
sheet.insertRule(rule, 0).Copy the code

Make sure it is called in the main function.

void main() {
    querySelector('#output').text = 'Hello, Dart! ';
    alignImageProperly();
    addHeader();
    addStyleElement();
}
Copy the code

Save and refresh your browser and the list should look better!

Here’s what your addStyleElement function looks like for reference.

addStyleElement() {
    var styleElement = new StyleElement().document.head.append(styleElement); .document.head.append(styleElement).CssStyleSheet sheet = styleElement.sheet; . CssStyleSheet sheet = styleElement.sheet;final rule = '.dogs { width: 150px; padding: 20px; margin-left: auto; margin-right: auto; display: block; } ';
    sheet.insertRule(rule, 0);  
}
Copy the code

Now, let’s solve the problem of names not beginning with a capital letter. With Dart, we can get a reference to the list and then fix the case of each item by name.

First, create a new function called fixCase that looks like this.

fixCase() {
    var listElementChildren = querySelector('.dogs').children[1].children;

    listElementChildren.asMap().forEach((idx, value) {
        listElementChildren[idx].text = "${value.text[0].toUpperCase()}${value.text.substring(1)}";
    });
}
Copy the code

Make sure it is called in the main function. Save your changes and refresh your browser. You should see something like this.

There’s a lot going on in this short code, so let’s take a closer look

We start by creating a reference to the child element of the second child element of the

that contains our list of names. The title that we added earlier is the 0th or first child of the element. The second child element is the list of names, and we need to get its children, because their case needs to be fixed.

Once we have the reference, we create a map and, using the Dart string interpolation syntax, we can hold each element in place. Since the reference we get is directly linked to the DOM, the value of the list changes immediately without further intervention.

Fixed horrible page titles

Update the page title in the main function to say something more appropriate. You can put whatever you want. Mine’s changed.

Adjust the footer appropriately

The footer looks a little off, let’s fix the alignment. Create a new function called alignFooter with the following content.

alignFooter() {
    querySelectorAll('footer').first.style.setProperty("text-align"."center")。
}
Copy the code

Make sure it is invoked in main, then save and refresh the browser. The footers should now be properly aligned.

This time, we use querySelectorAll, which is a very handy function that selects all the elements that meet the criteria. In our example, we have to use the first keyword to give us the first element in the list, because we know we only have one footer on the page. From there, the same process was used earlier to set the style properties to align the footer content.

Correct spelling errors in a large section of text

Have you ever noticed that you misspelled official under your feet? How do we find it and fix it?

Let’s create a function called fixSpelling and call it from main.

fixSpelling() {
    var p = querySelector('footer').querySelector('p');
    p.innerHtml = p.innerHtml.replaceFirst('offical'.'official');
}
Copy the code

Save and refresh, and you should see the following output.

The spelling is fixed! But, our link disappeared? That’s not very useful. Dart was built with security in mind, and by default does not allow things like a href to be added dynamically to the node tree.

We need to make some code changes here.

fixSpelling() {
    var p = querySelector('footer').querySelector('p');
    p.setInnerHtml(p.innerHtml.replaceFirst('offical'.'official'), treeSanitizer: AllowAllTreeSanitizer());
}

class AllowAllTreeSanitizer implements NodeTreeSanitizer {
    void sanitizeTree(Node node) {}
}
Copy the code

In our scenario, we want to allow all changes to happen on our site because we control the code and know what happens. We can then override the Sanitizer inside Dart with our own, blank implementation, which will allow anything to be added to the DOM.

This also happens to be an example of a named parameter in Dart. Did you notice the name treeSanitizer: ParamEnter? Dart allows you to specify which parameters you want to assign, which is really handy when you’re dealing with optional parameters and don’t want to affect any other parameters, although functions can accept other parameters as well.

The output of these code changes should be.

Build our web application

So far, we’ve been using WebDev as our compile and deploy — compile and deploy — change as we go, which is great for development. However, this is not a good way to deploy our Web application. Before deploying our application, we need to build it and create the deployment artifacts that we need to serve through the Web server.

Press Ctrl-c (Break) to stop WebDev serve. The Webdev tool can also be used to generate these artifacts. To build the project, execute the following command in the root directory of the project.

webdev build
Copy the code

In the output, you’ll see a line like this.

[INFO] Creating merged output dir 'build' completed, took 147ms
Copy the code

If you examine the newly created Build folder, you’ll see that WebDev has already created the deployment artifacts we need.

Deploy our web application

Deploying our Web application is a very simple task. The WebDev tool has created all the deployment artifacts we need, and we just need to upload these to our Web server. We can remove files that do not need to be deployed to the server, such as hidden configuration files and package folders.

Deployment Artifacts.

Copy or upload these files to your favorite web server, and your application is up and running. An easy way to do this is to use Github Pages. Pages is great for Web applications running in a browser and does not require server-side code to execute.

I’ve deployed the app we built to the Github page, which you can view in real time by clicking on the link.

conclusion

This is a short introduction to building a very basic Web application using Dart. The biggest win for me was that I was able to build the Web console I needed in the same language I built mobile applications in. I hope you learn something, and I hope you learn more about Dart.

Of course, there are also web application frameworks available for Dart. I’ll list some in the resources section below.

Resources section

  • Dart: VueDart supports vue.js
  • Dart support for Angular: AngularDart
  • A collection of Dart libraries and frameworks: Awesome Dart

Translated through (www.DeepL.com/Translator) (free version)