Planet Dart

the unofficial alterslash-style digest

core-drawer-panel drawer is transparent

Dart Questions Sunday January 04, 2015 @ 20:05 • over a year ago

I am trying to learn Polymer.dart and I am stuck at basic usage of core-drawer-panel... When I am using core-drawer-panel like this:

<link rel="import" href="../../packages/polymer/polymer.html">

<link rel="import" href="../../packages/core_elements/core_drawer_panel.html">
<link rel="import" href="../../packages/core_elements/core_header_panel.html">
<link rel="import" href="../../packages/core_elements/core_toolbar.html">
<link rel="import" href="../../packages/core_elements/core_menu.html">
<link rel="import" href="../../packages/core_elements/core_icons.html">
<link rel="import" href="../../packages/core_elements/core_item.html">
<link rel="import" href="../../packages/paper_elements/paper_icon_button.html">

<polymer-element name="main-app">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>
    <core-drawer-panel>
      <core-header-panel drawer>
        <core-toolbar>
          <div>Application</div>
        </core-toolbar>
        <core-menu>
          <core-item icon="settings">Test</core-item>
        </core-menu>
      </core-header-panel>
      <core-header-panel main>
        <core-toolbar>
          <paper-icon-button icon="menu" core-drawer-toggle></paper-icon-button>
          <div>Title</div>
        </core-toolbar>
        <div> Main content... </div>
      </core-header-panel>
    </core-drawer-panel>
  </template>
  <script type="application/dart" src="main_app.dart"></script>
</polymer-element>

I get transparent drawer, when the layout switches to narrow and drawer is displayed using button, so for example menu inside drawer area is superimposed over main content area... What am I missing here?

How to create a StreamTransformer in Dart?

Dart Questions Sunday January 04, 2015 @ 13:15 • over a year ago

Trying to build a custom StreamTransformer class, however a lot of the examples out there seem to be out of date, and the one found in the documentation isn't (what some typed languages might consider anyway) as a class (found here: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:async.StreamTransformer). This doesn't seem like a very Dart-like way of approaching it and rather more of a Javascript-like way (which I'm using Dart to avoid).

Many online sources say this is how you create a StreamTransformer, however there errors when extending it.

class exampleStreamTransformer extends StreamTransformer
{
  //... (This won't work)
}

'Implements' seems to be the way to go, along with implementing the bind function needed:

class exampleStreamTransformer implements StreamTransformer
{
  Stream bind(Stream stream)
  {
    //... (Go on to return new stream, etc)
  }
}

I can't seem to find any examples of this way, but have thrown something together myself (which is accepted in my IDE, but isn't accepted at runtime, I get a null object error when it tries to use pause getter):

class exampleStreamTransformer implements StreamTransformer
{
  StreamController<String> _controller;
  StreamSubscription<String> _subscription;

  Stream bind(Stream stream)
  {
    _controller = new StreamController<String>(
        onListen: ()
        {
          _subscription = stream.listen((data)
          {
            // Transform the data.
            _controller.add(data);
          },
          onError: _controller.addError,
          onDone: _controller.close,
          cancelOnError: true); // Unsure how I'd pass this in?????
        },
        onPause: _subscription.pause,
        onResume: _subscription.resume,
        onCancel: _subscription.cancel,
        sync: true
    );

    return _controller.stream;
  }
}

Would like to achieve it this way, as in the 'typed' way of producing the class, any help is much appreciated, thank you.

When to use part/part of versus import/export in Dart?

Dart Questions Sunday January 04, 2015 @ 07:21 • over a year ago

I do not completely understand the difference between part/part of and import/export when using libraries in Dart. For example:

    one.dart:
    library one;
    part “two.dart”;
    Class One {
    };

    two.dart:
    part of one;
    import 'somefile.dart';
    Class Two {
    }

versus

    library one;
    import 'two.dart';
    Class One {
    }

    library two;
    import 'somefile.dart';
    export 'somefile.dart';
    Class Two {
    }

Both scenarios seem to do the same thing. When is it advantageous to use part/part of rather than import, and are there scenarios where import will not work, but part/part of will?

Dart classes for models from JSON (code generation)

Dart Questions Saturday January 03, 2015 @ 21:41 • over a year ago

I was looking at this thread: https://groups.google.com/a/dartlang.org/forum/#!topic/misc/0pv-Uaq8FGI but still cannot find a solution for what I would like to have on the client side (possible on the server as well).

I imagine there should be a way to provide a standard format for data structure that is represented as JSON object in JS land (for example json schema or yaml or whatever) that could be used as input to generate Dart classes that contain the fromJSON constructor and toJSON method (possible some checks as well for the data ranges) that the developer can then extend if additional logic is needed over the data coming over the wire.

I do not want to use mirrors if possible, instead the classes should be statically generated (i.e. run a tool -> get the class(es) to match the latest schema/input).

Can you point me to the right direction?

Thanks.

PolymerElement Constructor

Dart Questions Saturday January 03, 2015 @ 14:14 • over a year ago

I'm trying to change the standard constructor to add myConstructor.

Based on the code here I coded the following statements:

@CustomTag('main-app')
class MainApp extends PolymerElement {

  factory MainApp.custom() {
    MainApp = new Element.tag('main-app');
    myConstructor();
  }
MainApp.created() : super.created();
void myConstructor() {
    print("myConstructor Started");
  }

Unfortunately the Editor shows some problems:
The Statement MainApp = new Element.tag('main-app') shows the error:
A Value of Type 'Element' cannot be assigned to a variable of type 'Type'.

The Statement myConstructor() shows the Error:
"Instance members cannot be accessed from a factory constructor"

anyone has a suggestion how I can solve the errors?

EDIT: The current code is looking like following:

@CustomTag('main-app')
class MainApp extends PolymerElement {

  @observable int counter = 0;


      factory MainApp.custom() {
    MainApp mainApp = new Element.tag('main-app');
    mainApp.myConstructor();
    return mainApp;
  }

  /// Constructor used to create instance of MainApp.
  MainApp.created() : super.created();

MainApp ma = new MainApp.custom();

  void myConstructor() {
    print("myConstructor Started");
    counter = 1;
  }

The following error is showing up:

Exception: type 'HtmlElement' is not a subtype of type 'MainApp' of 'mainApp'.
  MainApp.MainApp.custom    
  MainApp.MainApp.created

EDIT Version 2:

@CustomTag('main-app')
class MainApp extends PolymerElement {

  Controller controller = new Controller();

  @observable int counter = myConstructor();
  @observable int totalGlypto = 0;

  /// Constructor used to create instance of MainApp.
  MainApp.created() : super.created();


    static int myConstructor() {
    print("myConstructor Started");
    return controller.getTotal();
  }

  void setupCheckIn(Event e, var detail, Node target) {
    print("Setup started");
    controller.checkInGlypto();
    counter = controller.getTotal();
  }

  void resetCheckIn(Event e, var detail, Node target) {
    print("reset started");
  }

  void loadCheckIn(Event e, var detail, Node target) {
    print("load started");
    controller.loadData();
    counter = controller.getTotal();
  }


}

the code can be downloaded here

Dart Map with String key, compare with ignore case

Dart Questions Saturday January 03, 2015 @ 12:00 • over a year ago

Does the Map class in Dart have a way to ignore case if the key is a string?

Eg.

var map = new Map<String, int>(/*MyComparerThatIgnoresCase*/);
map["MyKey"] = 42;
var shouldBe42 = map["mykey"];

In C# the Dictionary constructor takes a comparer like the comment above. What is the canonical way to do this in Dart?

Using --enable-async with pub

Dart Questions Saturday January 03, 2015 @ 02:20 • over a year ago

I'm using the new async/await syntax in my code, and everything is working great if I run my application directly from dart using something like C:\dart\dart-sdk\bin\dart.exe --enable_async --checked C:\code\dart-app\main.dart

When I try to run pub run main.dart on the same application, however, I get an error message error: line XX pos XX: use flag --enable-async to enable async/await features. The --enable-async flag seems to be something for Dart itself, so I can't add it to the pub command. How can I build my application using pub in a way that allows me to us the async/await syntax?

Dart: mixin composition without extension

Dart Questions Friday January 02, 2015 @ 22:32 • over a year ago

I understand Dart mixins must not extend other classes. However, is there some way to create a composition of two mixins in some way that doesn't use an extend? For example, consider the following code

abstract class GreeterMixin{
  sayHello(String person) => print("Hello $person");
}

abstract class SmallTalkerMixin implements GreeterMixin{
  makeSmallTalk(String person){
    sayHello(person);
    print("The weather looks good");
  }
}

class Animal{
  final int nLegs;
  Animal(this.nLegs);
}

class Person extends Animal{
  final String name;
  Person(this.name): super(2);
}

class SocialPerson extends Person with GreeterMixin, SmallTalkerMixin{
  SocialPerson(String name): super(name);

  introduceSelf(String person){
    makeSmallTalk(person);
    print("My name is $name");
  }
}

Clearly, a smallTalker must be a greeter, but because I want to use SmallTalkerMixin as a mixin, it cannot extend GreeterMixin. Unfortunately, this means that everywhere I include SmallTalkerMixin as a mixin, I must also include GreeterMixin as a mixin.

In other words, is there a way to acheive the following using just the code above?

abstract class SmallTalkerGreeterMixin implements SmallTalkerMixin, GreeterMixin{
  sayHello(String person) => print("Hello $person");

  makeSmallTalk(String person){
    sayHello(person);
    print("The weather looks good");
  }
}

Dart pub trigger transformer build

Dart Questions Friday January 02, 2015 @ 20:17 • over a year ago

I'm using Sass in my dart project and build the scss files to css using a transformer. The scss files can import other files so when a scss file is changed all scss files that import the changed file also have to be updated. Currently I run the touch cmd to trigger an update on the other files but this causes issues with text editors thinking the file data has changed. Is there a way to trigger pub to rebuild specific files?

Procedural Generation - Part One - Making A Dungeon

Davy Mitchell (Diving into Dart) Friday January 02, 2015 @ 19:59 • over a year ago

Procedural generation is a technique used in computer graphics, simulations and games to create content on demand. For example, the worlds in Minecraft are not installed with the game, they are created by algorithms whilst the game is being played. Often the algorithms introduce variations to allow unique content to be created every time the game is played. Fractals are an example of procedural generation as are many on the HTML5 demos on this blog.

This is the first in a series looking at Procedural Generation using Dart. The example will be generating a 2D dungeon as might be found in a game such as NetHack.

First step is to create some utility classes to create a map and store information at each point.


// Block is the smallest unit of a map.
class block {
int base = VOID;
block(this.base);
}

// Point - cell on the map.
class point {
int x = 0;
int y = 0;
point(this.x, this.y) {}
}


// Rectangle - defines a rectangular area on the map.
class rectangle {

int x = 0;
int y = 0;
int width = 0;
int height = 0;
int x2 = 0;
int y2 = 0;

rectangle(this.x, this.y, this.width, this.height) {update2ndPoints();}

point getMidPoint() => (new point(x + (width / 2).round(), y + (height / 2).round()));

void update2ndPoints() {
x2 = x + width;
y2 = y + height;
}
}

The generation algorithm will add a requested number of rooms and then connect them via corridors. Walls will then be added around rooms and corridors. Finally corners where walls meet are marked on the map. Of course, we want to actually see the dungeon so to start with will display it in text in a much simplified form.

Code is available on Github and a live demo is available here. Hitting the button a few times shows how many varied dungeons can be.

Next time we will look at providing a Canvas display instead of text.

How do I open and follow a file in Dart (like tail -f)?

Dart Questions Friday January 02, 2015 @ 19:42 • over a year ago

Is there an easy way to open a file and continously read from it without the stream getting closed on EOF? Like the Unix command tail -f.

Just reading until EOF is described in the API docs. But I can't see an obvious/simple way to block or pause the stream for more input.

One solution would be to repeatedly reopen the file and continue reading from the last known length when I detect that the file size has changed.

So I have my dart file like this which is just supposed to simply render a small image onto a canvas, but nothing appears in the Dartium tab that loads when I run it.

class Tfc {
  GameMap map;
  CanvasRenderer renderer    = new CanvasRenderer(width: 1024, height: 1024);
  Stage stage       = new Stage(new Colour.fromHtml('#ffffff'));
  Sprite wood       = new Sprite.fromImage('wood_ph.png');
  Sprite void_tile = new Sprite.fromImage('void_ph.png');
  Graphics graph = new Graphics();

  Tfc() {
    stage.children.add(graph);
    document.body.append(this.renderer.view);
    wood.position = new Point(0,0);
    stage.children.add(wood);
    renderer.render(stage);
  }

  void main() {
    map = new GameMap(32, 32);

    for (int i = 0; i < 32; i++) {
      for (int j = 0; j < 32; j++) {
        _addTile(i, j);
      }
    }
    print("CALLING CTOR");
    new Tfc();
  }

This is my html file, very simple at the moment as you can see.

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PixiTest</title>

    <script async type="application/dart" src="app.dart"></script>
    <script async src="packages/browser/dart.js"></script>

    <link rel="stylesheet" href="app.css">
  </head>
  <body>
  </body>
</html>

I would be grateful if someone could point out the error/omission in my code.

Call Dart function from C

Dart Questions Friday January 02, 2015 @ 17:47 • over a year ago

I want to call a Dart method from c++ extension. Is it possible?

Dart code:

void someNativeMethod(Function callback) native "someNativeMethod";

void callback() {
    print("Hello world!");
}

void main() {
    someNativeMethod(callback);
}

C code:

void someNativeMethod(Dart_NativeArguments args) {
    Dart_Handle callbackHandle = Dart_GetNativeArgument(args, 0);
    // Now i want to call the callback
}

Dart2JS and Enumerators

Dart Questions Friday January 02, 2015 @ 10:56 • over a year ago

I'm using enumerators (experimental) in my project. Pub Build (Generate JS) in my Dart Editor does not work due to the enums. In my console, this command:

dart2js file.dart --enable-enum

does work, but it is inconvinient to do it through the console. Is there any way to add arguments to the default command in Dart Editor (--enable-enums) so it'd allow it to compile into JS?

Running it by default in Dartium works and when copying and pasting the server url (http://localhost:8080/index.html), the dart2js is triggered and it starts working (after average compilation time).

EDIT: Yes, I have enums enabled in my editor.

EDIT2: To enable enums in dart2js, I have this transformer in pubspec.yaml:

transformers:
- $dart2js:
    commandLineOptions: [--enable-enum]

However, I get this error in a file, which uses enums:

Directive not allowed here.
part of thing;
^^^^^^^^^^^^^^^^
[Info from Dart2JS]:

It's weird that it works in the console with the same arguments and not in the editor.

I have filled a bug report here.

A web component inside the template of another

Dart Questions Friday January 02, 2015 @ 10:10 • over a year ago

I have a custom element, which is extended by 2 other custom elements

import 'dart:html';

void main() {
  document.registerElement('x-c', C);
  document.registerElement('x-b', B);

}

class ViewBase extends HtmlElement{
  TemplateElement t;
  ViewBase.created():super.created(){
    t = this.querySelector('template');
    var clone = t.content.clone(true);
    this.createShadowRoot();
    this.shadowRoot.append(clone);
  }
}

class B extends ViewBase{
  B.created():super.created();
}

class C extends ViewBase{
  C.created():super.created();
}

when i try to do something like the following

<x-b>
    <template>
       <p>this is a paragraph in b shadowroot</p>
       <x-c>
         <template>
            <p>this is a paragraph in c shadowroot</p>
         </template>
       </x-c>
    </template>
 </x-b>

the nested C element constructor never gets called when the super constructor activates the template inside the B element, any idea why?

what i expect to see on the page is

this is a paragraph in b shadowroot
this is a paragraph in c shadowroot

what i get is only

this is a paragraph in b shadowroot
pluto/1.3.2 - Ruby/2.0.0 (2014-11-13/x86_64-linux) on Sinatra/1.4.5 (production)