Simple Dart Web Component Not Working

2019-08-05 07:46发布

问题:

Short Version: The custom web component example in the first link isn't working for me. Why not? I'm running this in Dartium.

Long Version: I copied and pasted this Dart Web UI example from this tutorial into the Dart Editor and tried to run it. Nothing showed up on the page. I've used dart before but not with web components, so I noticed that one difference between this code and other code I've written is that there was no <script src="packages/browser/dart.js"></script>, so I added that at the bottom. Now I got the error:

Internal error: Dart_Invoke: did not find top-level function 'main'.

I put a print statement in the main() function, and the text was printed before the error, which is strange. I guessed and tried adding main() {} inside the <script> tag that was in the custom component. That is, the script tag looked like:

<script type="application/dart">
  import 'package:web_ui/web_ui.dart';

  main() {print("in main in component");}
  class CounterComponent extends WebComponent {
    int count = 0;
    void increment() { count++; }
  }
</script>

Now that error goes away, and both print statements are printed, but nothing happens.

Here is the original tutorial code for your convenience:

<!DOCTYPE html>
<!--
Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
for details. All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
-->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet"
    href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css">
</head>
<body>
  <element name="click-counter" constructor="CounterComponent" extends="div">
    <template>
      <button on-click="increment()">Click me</button>
      <span>(click count: {{count}})</span>
    </template>
    <script type="application/dart">
      import 'package:web_ui/web_ui.dart';

      class CounterComponent extends WebComponent {
        int count = 0;
        void increment() { count++; }
      }
    </script>
  </element>
  <div class="well">
    <div is="click-counter"></div>
  </div>
  <script type="application/dart">
    main(){}
  </script>
</body>
</html>

回答1:

Web UI applications need to be "built" (usually by a script called build.dart in the project root, see this article for more details).

If I go to the Dart Editor, create a new test project using the wizard and selecting the Web Project (using the web_ui library) option, this creates the boilerplate including the build script.

Open up the html file and paste in the code from the github tutorial, replacing what is there already. When you save the file, the build.dart will be invoked, outputting the build version to /web/out/

Hit the run button, and the Dart Editor will open the app in Dartium (it knows to add /out/ to the URL).