Dart 与 HTML 关联

This tutorial is the first of a series onbasic, low-level web programming with the dart:html library.If you use a web framework like AngularDart,some of these concepts might be useful,but you might not need to use the dart:html library at all.

What’s the point?

  • DartPad lets you write a simple Dart web app without HTML boilerplate.
  • A Dart web app has Dart, HTML, and (usually) CSS code.
  • Compile a web app’s Dart code to JavaScript to run the app in any modern browser.
  • An HTML file hosts your Dart code in a browser page.
  • The DOM models a browser page in a tree/node structure.
  • Use querySelector() with an ID to get an element from the DOM.
  • CSS selectors are patterns used to select matching elements in the DOM.
  • Use CSS rules to style elements.

To write a low-level web app with Dart,you need to understandseveral topics—the DOM tree, nodes, elements,HTML, and the Dart language and libraries.

The interdependencies are circular,but we have to begin somewhere,so we begin with a simple HTML file,which introduces the DOM tree and nodes.From there,you build a bare bones, stripped-downDart appthat contains just enough code todynamically put text on the page from the Dart side.

Though simple,this example shows you how to connect a Dartapp to an HTML page andone way that a Dart app can interact with items on the page.These concepts provide the foundationfor more interesting and useful web apps.

About the Dart, HTML, and CSS triumvirate

If you’ve usedDartPad,you’ve already seen the DART, HTML, and CSS tabsthat let you write the code for a web app.Each of these three languagesis responsible for a different aspect of the web app.

LanguagePurpose
DartImplements the interactivity and dynamic behavior of the web app
HTMLDescribes the content of the web app’s page (the elements in the document and the structure)
CSSGoverns the appearance of page elements

A Dart program canrespond to events such as mouse clicks,manipulate the elements on a web page dynamically,and save information.Before the web app is deployed,the Dart code must be compiled into JavaScript code.

HTML is a language for describing web pages.Using tags, HTML sets up the initial page structure,puts elements on the page,and embeds any scripts for page interactivity.HTML sets up the initial document treeand specifies element types, classes, and IDs,which allow HTML, CSS, and Dart programs to refer to the same elements.

CSS, which stands for Cascading Style Sheets, describes the appearanceof the elements within a document.CSS controls many aspects of formatting:type face, font size, color, background color,borders, margins, and alignment, to name a few.

About the DOM

The Document Object Model (DOM)represents the structure of a web document as a tree of nodes.When an HTML file is loaded into a browser,the browser interprets the HTMLand displays the document in a window.The following diagram shows a simple HTML file andthe resulting web browser page in Chrome.

A simple HTML file and its resulting web page

HTML uses tags to describe the document.For example, the simple HTML code aboveuses the <title> tag for the page title,<h1> for a level-one header,and <p> for a paragraph.Some tags in the HTML code,such as<head> and <body>,are not visible on the web page,but do contribute to the structure of the document.

In the DOM,the document object sits at the root of the tree(it has no parent).Different kinds of nodes in the treerepresent different kinds of objects in the document.For example, the tree has page elements,text nodes, and attribute nodes.Here is the DOM tree for the simple HTML file above.

The DOM tree for a simple HTML file

Notice that some tags, such as the <p> paragraph tag,are represented by multiple nodes.The paragraph itself is an element node.The text within the paragraph is a text node(and in some cases, might be a subtree containing many nodes).And the ID is an attribute node.

Except for the root node, each node in the tree has exactly one parent.Each node can have many children.

An HTML file defines the initial structure of a document.Dart or JavaScript can dynamically modify that documentby adding, deleting, and modifying the nodes in the DOM tree.When the DOM is changed,the browser immediately re-renders the window.

A Dart program can dynamically change the DOM

The diagram shows a small Dart program that makesa modest change to the DOM by dynamicallychanging a paragraph’s text.A program could add and delete nodes,or even insert an entire subtree of nodes.

Create a new Dart app

  • Go to DartPad.
  • Click the New Pad button to undo any changes you might have madethe last time you visited DartPad.
  • Select the Show web content checkbox at the bottom right corner,so you can edit HTML and CSS in DartPad.

Note:These instructions feature DartPad,which hides some of the HTML boilerplate code.If you want to use any other editor,then we recommend starting with a small Dart web app sampleand modifying the non-script tags inside the <body> section.HTML and Dart connections shows the full HTML code.

Edit the HTML source code

  • Click HTML, at the upper left of DartPad.The view switches from Dart code to the (non-existent) HTML code.

  • Add the following HTML code:

  1. <p id="RipVanWinkle">
  2. RipVanWinkle paragraph.
  3. </p>
  • Click HTML OUTPUT to see how a browser would render your HTML.

About the HTML source code

This HTML code is similar to the HTML code in thevarious diagrams earlier in this tutorial,but it’s even simpler.

In DartPad you need only the tags you really care about—inthis case, <p>.You don’t need surrounding tags such as<html> and <body>.Because DartPad knows where your Dart code is,you don’t need a <script> tag.

Note:HTML and Dart connections shows the full HTML codethat you need to run your web app outside of DartPad.

The paragraph tag has the identifier “RipVanWinkle”.The Dart code you create in the next step uses this IDto get the paragraph element.

Edit the Dart source code

  • Click DART, at the upper right of DartPad.The view switches from HTML code to Dart code.

  • Change the Dart code to the following:

  1. import 'dart:html';
  2.  
  3. void main() {
  4. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';
  5. }
  • Click Run to execute your code.

The text in the HTML OUTPUT tab changes to “Wake up, sleepy head!”

About the Dart source code

Let’s step through the Dart code.

Importing libraries

The import directive imports the specified library,making all of the classes and functionsin that libraryavailable to your program.

  1. import 'dart:html';

This program imports Dart’s HTML library,which contains key classes and functions for programming the DOM.Key classes include:

Dart classDescription
NodeImplements a DOM node.
ElementA subclass of Node; implements a web page element.
DocumentAnother subclass of Node; implements the document object.

The Dart core library contains another useful class:List,a parameterized class that can specify the type of its members.An instance of Element keeps its list of child Elementsin a List<Element>.

Using the querySelector() function

This app’s main() function contains a singleline of code that is a little like a run-on sentencewith multiple things happening one after another.Let’s deconstruct it.

querySelector() is a top-level function provided by the Dart HTML librarythat gets an Element object from the DOM.

  1. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';

The argument to querySelector(), a string,is a CSS selector that identifies the object.Most commonly CSS selectors specify classes, identifiers, or attributes.We’ll look at these in more detail later,when we add a CSS file to the mini app.In this case, RipVanWinkle is the unique ID for a paragraph elementdeclared in the HTML file,and #RipVanWinkle specifies that ID.

  1. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';

Another useful function for getting elements from the DOMis querySelectorAll(),which returns multiple Element objects viaa list of elements—List—allof which match the provided selector.

Setting the text of an Element

In the DOM, the text of a page element is containedin a child node, specifically, a text node.In the following diagram,the node containing the string“RipVanWinkle paragraph.”is a text node.

DOM tree for a paragraph element

More complex text,such as text with style changes orembedded links and images,would be represented with a subtree of text nodes and other objects.

In Dart,you can simply use the Element text property,which has a getterthat walks the subtree of nodes for you and extracts their text.

  1. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';

However, if the text node has styles (and thus a subtree),getting text and then setting it immediately is likelyto change the DOM, as a result of losing subtree information.Often, as with our RipVanWinkle example,this simplification has no adverse effects.

The assignment operator (=) sets the textof the Element returned by the querySelector() functionto the string “Wake up, sleepy head!”.

  1. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';

This causes the browser to immediately re-renderthe browser page containing this app, thusdynamically displaying the text on the browser page.

HTML and Dart connections

The Dart web app changedthe text in the browser window dynamically at runtime.Of course, placing text on a browser pageand doing nothing elsecould be accomplished with straight HTML.This little app only shows you how to make a connectionfrom a Dart app to a browser page.

In DartPad, the only visible connection betweenthe Dart code and the HTML codeis the RipVanWinkle ID.

The RipVanWinkle ID is used by both Dart and HTML

To run your app outside of DartPad, you need to compile your Dartcode to JavaScript. Use the webdev build commandto compile your app to deployable JavaScript.Then you need to make another connection between the HTML andgenerated JavaScript: you must add a <script> tag to the HTMLto tell the browser where to find the compiled Dart code.

Here’s the full HTML code for this app,assuming that the Dart code is in a file named main.dart:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>A Minimalist App</title>
  5. <script defer src="main.dart.js"></script>
  6. </head>
  7. <body>
  8. <p id="RipVanWinkle">
  9. RipVanWinkle paragraph.
  10. </p>
  11. </body>
  12. </html>

The <script> element specifies the location of the compiled Dart code.

Give the app some style with CSS

Most HTML uses cascading style sheets (CSS) to define _styles_that control the appearance of page elements.Let’s customize the CSS for the mini app.

  • Click CSS.The view switches from Dart code to the (non-existent) CSS code.

  • Add the following CSS code:

  1. #RipVanWinkle {
  2. font-size: 20px;
  3. font-family: 'Open Sans', sans-serif;
  4. text-align: center;
  5. margin-top: 20px;
  6. background-color: SlateBlue;
  7. color: Yellow;
  8. }

The display under HTML OUTPUT immediately changesto reflect the new styles,which apply only to the page elementthat has the ID RipVanWinkle.

About CSS selectors

IDs, classes, and other information about elementsare established in HTML.Your Dart code can use this informationto get elements using a CSS selector—a patternused to select matching elements in the DOM.CSS selectors allow the CSS, HTML, and Dart codeto refer to the same objects.Commonly, a selector specifies an ID,an HTML element type,a class, or an attribute.Selectors can also be nested.

CSS selectors are important in Dart programsbecause you use them with querySelector() and querySelectorAll()to get matching elements from the DOM.Most often Dart programs use ID selectors with querySelector()and class selectors with querySelectorAll().

Here are some examples of CSS selectors:

Selector typeExampleDescription
ID selector#RipVanWinkleMatches a single, unique element
HTML elementpMatches all paragraphs
HTML elementh1Matches all level-one headers
Class.classnameMatches all items with the class classname
Asterisk*Matches all elements
Attributeinput[type=”button”]Matches all button input elements

Tip:As you saw,the mini app used a CSS selector,the ID #RipVanWinkle,even when there was no CSS file.You do not need a CSS file for a Dart program.Nor do you need a CSS file to use CSS selectors.CSS selectors are established in the HTML fileand used by the Dart programto select matching elements.

Let’s look at the CSS code for the mini app.The CSS file for the mini app has one CSS rule in it.A CSS rule has two main parts: a selector and a set of declarations.

The parts of a CSS rule

In the mini app, the selector #RipVanWinkle is an ID selector,as signaled by the hash tag (#);it matches a single, unique element with the specified ID,our now tired RipVanWinkle paragraph element.RipVanWinkle is the ID in the HTML file.It is referred to in the CSS file and in the Dart codeusing a hash tag(#).Classnames are specified in the HTML file without a period (.)and referred to in the CSS file and in Dart code with a period (.).

Between the curly brackets of a CSS rule isa list of declarations,each of which ends in a semi-colon (;).Each declaration specifies a property and its value.Together the set of declarations define the _style sheet_for all matching elements.The style sheet is used to set the appearanceof the matching element(s) on the web page.

A declaration specifies an attribute and its value

The CSS rule for the RipVanWinkle paragraphspecifies several properties;for example, it sets the text color to Yellow.

Other resources

What next?

The next tutorial, Add elements to the DOM,shows you how to dynamically change the HTML pageby adding elements to the DOM.