Search code examples
htmldartdart2js

How to use a dartscript on your website


Hello i just started to learn some dart and im new in this forum aswell,

i've created the ubersimple webapp, with webstorm and written a really simple dart script and a html document.

the head of my html doc:

<!DOCTYPE html>
<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>Das bist du!</title>
   <script defer src="http://das-bist-du.com/main.dart" type="application/dart"></script>
   <script defer src="http://das-bist-du.com/packages/browser/dart.js">    </script>
 </head>

<body>
</body>
</html>

the dart code:

import 'dart:html';
import 'dart:math';

ButtonElement rndButton;
ImageElement rndImage;  
var images;
var rng;

void main() {
  rndButton = querySelector('#rndButton');
  rndImage = querySelector('#imgScreen');

  images = ['http://das-bist-du.com/onewebmedia/anN0MBo_700b.jpg', 'http://das-bist-du.com/onewebmedia/du1.jpg', 'http://das-bist-du.com/onewebmedia/du2.jpg', 'http://das-bist-du.com/onewebmedia/du3.jpg', 'http://das-bist-du.com/onewebmedia/du3.jpg', 'http://das-bist-du.com/onewebmedia/du4.jpg', 'http://das-bist-du.com/onewebmedia/du5.jpg', 'http://das-bist-du.com/onewebmedia/du6.jpg'];
  rndButton.onClick.listen(pickYou);
}
 void pickYou (Event e) {
  rng = new Random();
  setYou(rng.nextInt((images.length)));
}

void setYou (var rnd) {
  print(images[rnd].toString());
  rndImage.src =  (images[rnd].toString());
}

I know the code is not pretty and all, i was just testing things out. :)

Now i want to use both on a website, i uploaded the html page the code and the dart.js to the website and put the src in the html script tag.

When testing in Webstorm with Chromium it works. But the script dont run on the website. How can i use dart online on a website?

Thanks in advance


Solution

  • Dart doesn't run in any browser directly except Dartium (the Chomium based Dart development browser that includes the Dart VM).

    When you run pub build in your project directory (where the pubspec.yaml is) then you get an output in the build sub-directory that can be uploaded to web servers for public use.

    There is also a transformer available that optimizes the script tags when pub build is run. https://pub.dartlang.org/packages/dart_to_js_script_rewriter