Planet Dart

Updated Monday, 05 January 2015 07:00
{}
Dart Questions ( Feed )
Sunday, 04 January 2015
core-drawer-panel drawer is transparent

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_elem

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?

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: api.dartlang.org/apidocs/channels/stab

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?

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 o

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 Questions ( Feed )
Saturday, 03 January 2015
Dart classes for models from JSON (code generation)

I was looking at this thread: 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

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

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.ta

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

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 construc

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

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

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 Questions ( Feed )
Friday, 02 January 2015
Dart: mixin composition without extension

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 pers

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

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

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

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 all

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)?

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

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.

Simple pixi program seems to produce nothing but a blank tab in Dartium. What am I doing wrong?

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: 10

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

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);
}


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

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

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

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.

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
Dart Object -> JSON String failing to convert to JSON

I'm trying to serialize an object to JSON and then back from JSON to object again.

This is the code snippet that is supposed to give me proper JSON:

 LoginRequest req = new LoginRequest();
    req.username = username;
    req.password = password;

I'm trying to serialize an object to JSON and then back from JSON to object again.

This is the code snippet that is supposed to give me proper JSON:

 LoginRequest req = new LoginRequest();
    req.username = username;
    req.password = password;
    req.created = 123456;
    req.test = "KOTS";
    print(req.toString());

What I'm seeing in the console is this:

{} (:1)

In pubspec.yaml I'm importing json_object as a dependency:

environment:
  sdk: '>=1.0.0 <2.0.0'
dependencies:
  ...
  json_object: any

I have a base message class that extends JsonObject:

import 'package:json_object/json_object.dart';

class Message extends JsonObject {

  int created = new DateTime.now().millisecondsSinceEpoch;

}

and then I have a LoginRequest that extends Message:

import 'Message.dart';

class LoginRequest extends Message {

  String _username;
  String _password;
  String test;

  String get username => _username;
  set username(String username) {
    _username = username.trim();  
  }

  String get password => _password;
  set password(String password) {
    _password = password.trim(); 
  }

}

I was thinking that only the base class will be converting to Json, so I wrote another test case:

Message msg = new Message();
msg.created = 123456;
print(msg.toString());

This is also printing:

{} (:1)

Calling objectToJson does the same:

objectToJson(msg).then((jsonStr) => print(jsonStr));
objectToJson(req).then((jsonStr) => print(jsonStr));

Outputs:

{}
{}

Removing extends JsonObject causes the above code to spew a stack trace:

Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0      _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3      JsonEncoder.convert (dart:convert/json.dart:243)
#4      JsonCodec.encode (dart:convert/json.dart:141)
#5      login (package:falm/login-dialog.dart:47:22)
#6      Function.apply (dart:core-patch/function_patch.dart:28)
#7      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8      invoke (package:smoke/smoke.dart:43:41)
#9      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10     BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.

NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2      objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3      objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4      login (package:falm/login-dialog.dart:43:17)
#5      Function.apply (dart:core-patch/function_patch.dart:28)
#6      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7      invoke (package:smoke/smoke.dart:43:41)
#8      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9      BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Clicked Login (:1)
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0      _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3      JsonEncoder.convert (dart:convert/json.dart:243)
#4      JsonCodec.encode (dart:convert/json.dart:141)
#5      login (package:falm/login-dialog.dart:47:22)
#6      Function.apply (dart:core-patch/function_patch.dart:28)
#7      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8      invoke (package:smoke/smoke.dart:43:41)
#9      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10     BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.

NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2      objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3      objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4      login (package:falm/login-dialog.dart:44:17)
#5      Function.apply (dart:core-patch/function_patch.dart:28)
#6      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7      invoke (package:smoke/smoke.dart:43:41)
#8      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9      BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Importing dart:convert and using JSON.encode does the same:

import 'dart:convert' show JSON;

...

  print(JSON.encode(msg));
  print(JSON.encode(req));

Outputs:

{}
{}

If I remove the extends JsonObject, then it throws a stack trace:

Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0      _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3      JsonEncoder.convert (dart:convert/json.dart:243)
#4      JsonCodec.encode (dart:convert/json.dart:141)
#5      login (package:falm/login-dialog.dart:47:22)
#6      Function.apply (dart:core-patch/function_patch.dart:28)
#7      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8      invoke (package:smoke/smoke.dart:43:41)
#9      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10     BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Clicked Login (:1)
Exception: Uncaught Error: Class '_LocalClassMirror' has no instance getter 'getters'.

NoSuchMethodError: method not found: 'getters'
Receiver: Instance of '_LocalClassMirror'
Arguments: []
Stack Trace:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      _serializeObject (package:json_object/src/mirror_based_serializer.dart:127:16)
#2      objectToSerializable (package:json_object/src/mirror_based_serializer.dart:53:21)
#3      objectToJson (package:json_object/src/mirror_based_serializer.dart:22:23)
#4      login (package:falm/login-dialog.dart:43:17)
#5      Function.apply (dart:core-patch/function_patch.dart:28)
#6      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#7      invoke (package:smoke/smoke.dart:43:41)
#8      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#9      BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#10     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#11     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#12     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Clicked Login (:1)
Exception: Uncaught Error: Converting object to an encodable object failed.
Stack Trace:
#0      _JsonStringifier.writeObject (dart:convert/json.dart:660)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:831)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:813)
#3      JsonEncoder.convert (dart:convert/json.dart:243)
#4      JsonCodec.encode (dart:convert/json.dart:141)
#5      login (package:falm/login-dialog.dart:47:22)
#6      Function.apply (dart:core-patch/function_patch.dart:28)
#7      GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#8      invoke (package:smoke/smoke.dart:43:41)
#9      HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#10     BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#11     _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#12     _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#13     BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)

Is JsonObject still the right way to go for serializing objects to JSON and deserializing JSON to objects? (I see in the code copyright 2013 which is ancient by now). If so, am I missing something in my classes?

In the dart cookbook there are examples where every class has its own toJson method and where all the values are manually copied into a map, this is cumbersome, if my whole app is JSON-driven, then I'll be spending most of my time writing boilerplate toJson / fromJson methods - this is exactly what I'm trying to get away from, hence the reason for choosing dart.

Furthermore I see examples on StackOverflow where mirrors are being used followed by comments that mirrors aren't fully supported in dart2js - since this is a browser based application, it is crucial that it can compile to javascript.

Update:

Based on Robert's answer, it seems doing the boilerplate is unavoidable:

Message.dart

import 'dart:convert' show JSON;

class Message {

  int created = new DateTime.now().millisecondsSinceEpoch;

  Map toJson() { 
    Map map = new Map();
    map["created"] = this.created;
    return map;
  }  

  String toString(){
    return JSON.encode(this);
  }

}

LoginRequest.dart

import 'Message.dart';

class LoginRequest extends Message {

  String _username;
  String _password;
  String test;

  String get username => _username;
  set username(String username) {
    _username = username.trim();  
  }

  String get password => _password;
  set password(String password) {
    _password = password.trim(); 
  }

  Map toJson() { 
    Map map = super.toJson();
    map["username"] = this.username;
    map["password"] = this.password;
    return map;
  }  

}

Test code:

LoginRequest req = new LoginRequest();
req.username = username;
req.password = password;
req.created = 123456;
req.test = "KOTS";
print(req);
// outputs: {"created":123456,"username":"asdfasdf","password":"adfasdf"} (:1)

Message msg = new Message();
msg.created = 123456;
print(msg);
// outputs: {"created":123456} (:1)

toString I only need to implement once on the Message class, toJson will need to go on every class.

docker -v and symlinks

I am on a Windows machine trying to create a Dart server. I had success building and image with my files with ADD and running the container. However, it is painful to build an image every time I wan't to test my code so I thought it would be better to mount

I am on a Windows machine trying to create a Dart server. I had success building and image with my files with ADD and running the container. However, it is painful to build an image every time I wan't to test my code so I thought it would be better to mount my files with the -v command since they are access live from my host machine at runtime.

The problem is that dart's packages folder at /bin/packages is really a symlink (if its called symlink in windows) and docker or boot2docker or whatever doesn't seem able to go past it and I get

Protocol error, errno = 71

I've used dart with GAE and the gcloud command somehow created the container, got your files in there and reacted to changes in your host files. I don't know if they used the -v option (as I am trying) or they have some auto-builder that created a new image with your files using ADD and the ran it, in anycase that seemed to work.

More Info

I've been using this Dockerfile that I modified from google/dart

FROM google/dart

RUN ln -s /usr/lib/dart /usr/lib/dart/bin/dart-sdk

WORKDIR /app

# ADD pubspec.* /app/
# RUN pub get
# ADD . /app
# RUN pub get --offline

WORKDIR /app/bin

ENTRYPOINT dart
CMD server.dart

As you see, most of it is commented out because instead of ADD I'd like to use -v. However, you can notice that on this script they do pub get twice, and that effectively creates the packages inside the container.

Using -v it can't reach those packages because they are behind host symlinks. However, pub get actually takes a while as it install the standard packages plus your added dependencies. It this the only way?

{}
Dart Questions ( Feed )
Thursday, 01 January 2015
type error when calling "send" on MidiOutput proxy

Apparently there's is a problem with the method navigator.requestMIDIAccess() in dart. code.google.com/p/dart/issues/detail?id=21805

So I tried the workaround using javascript proxies. Listing the midi ports on the console is no problem. However when I try to sen

Apparently there's is a problem with the method navigator.requestMIDIAccess() in dart. https://code.google.com/p/dart/issues/detail?id=21805

So I tried the workaround using javascript proxies. Listing the midi ports on the console is no problem. However when I try to send a midi note, an error gets raised: 'Type Error'

I can't find out howto pass the 'note-on' parameter? output.callMethod('send', [[144 , 60, 127]]); outputs[0] gives me "Microsoft GS Wavetable Synth"

import 'dart:html';
import 'dart:js';

void main() {
  final JsObject w = new JsObject.fromBrowserObject(window);
  final JsObject n = w['navigator'];

  if (n.hasProperty('requestMIDIAccess')) {
    n.callMethod('requestMIDIAccess').callMethod('then', [(JsObject midiAccess) {
        JsObject inputs = new JsObject.jsify(midiAccess.callMethod('outputs'));
        for (JsObject input in inputs) {
         print(input['name']);
        }
        ;
        sendMiddleC(midiAccess, 1);
      }]);
  }

}

void sendMiddleC(midiAccess, portID) {
  JsObject outputs = midiAccess.callMethod('outputs');
  JsObject output = outputs[0];
  output.callMethod('send', [[144 , 60, 127]]);
}
Interaction between Dart/Objective-C and Dart/Java

I read a really interesting article about how create cross-plateform app : www.skyscanner.net/blogs/developing-mobile-cross-platform-library-part-3-javascript

But I would prefere use Dart instead of Javascript, and I was wondering if it's possible to have interac

I read a really interesting article about how create cross-plateform app : http://www.skyscanner.net/blogs/developing-mobile-cross-platform-library-part-3-javascript

But I would prefere use Dart instead of Javascript, and I was wondering if it's possible to have interaction between Dart/Objc and Dart/Android, exactly in the same way that is showed in the article (run a Javascript VM to execute the javascript code).

Thanks

Perform Drive API requests

I want to list the files contained in a specific folder.

I have to make 3 requests...

drive.files.list(q: "'root' in parents and title = '_folder_A'").then((storage.FileList list_0) {
  drive.files.list(q: "'${list_0.items[0].id}' in parents and 

I want to list the files contained in a specific folder.

I have to make 3 requests...

drive.files.list(q: "'root' in parents and title = '_folder_A'").then((storage.FileList list_0) {
  drive.files.list(q: "'${list_0.items[0].id}' in parents and title = '_folder_a'").then((storage.FileList list_1) {
    drive.files.list(q: "'${list_1.items[0].id}' in parents").then((storage.FileList list_3) {
        print(list_3.items[0].title); // The good file
    });
  });
});

Do you have a better proposition ?

Watching an ObservableList

i have an

ObservableList<Model> models;

and i listen to changes as follows

models.listChanges.listen((changes){
      changes.forEach((change){
         print(change);
         List<Model> removedItems = chan

i have an

ObservableList<Model> models;

and i listen to changes as follows

models.listChanges.listen((changes){
      changes.forEach((change){
         print(change);
         List<Model> removedItems = change.removed; //a list of removed objects 
         //how to get a list of the items that have been added?
      });
    });

how to get a list of the items that have been added?

and sometimes i get notifications like the following, what does the index actually refer to?

#<ListChangeRecord index: 49, removed: [Instance of 'Model', Instance of 'Model'], addedCount: 19>

to get the added items my guess is

var addedItems = models.getRange(change.index,change.index+change.addedCount);`

but is that actually the right way?

gwt - dart - polymer integration

i have a developed gwt application and have it in production.

i would like to continue development in dart as developing/debugging seems way better to me than with gwt.

i already have written some modules in pure dart and am able to integrate the comp

i have a developed gwt application and have it in production.

i would like to continue development in dart as developing/debugging seems way better to me than with gwt.

i already have written some modules in pure dart and am able to integrate the compiled js in the gwt app. communication between gwt<->dart via json also works fine.

now i would like to integrate some dart/polymer elements but did not have any success doing it. is anybody doing this? is it possible? any hints?

this is my gwt host page. how do i get polymer imported/initialised/started?

<!doctype html>
<html>
  <script type="text/javascript" src="app/app.nocache.js"></script>

  </head>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div id="cwm" style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
    Your web browser must have JavaScript enabled
    in order for this application to display correctly.
      </div>
    </noscript>

    <!-- DART integration-->
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script src="dart_application/web/dart_plain.dart" type="application/dart"></script>
    <script src="dart_application/web/packages/browser/dart.js" type="text/javascript"></script>



  </body>
</html>
{}
Dart Questions ( Feed )
Wednesday, 31 December 2014
How to create an object from a function

I am trying to create a wrapper for lunr.js (lunrjs.com/) in Dart, however, I can find no documentation on how to use this with the Dart js interop.

This is the object I am trying to create:

var index = lunr(function () {
    this.

I am trying to create a wrapper for lunr.js (http://lunrjs.com/) in Dart, however, I can find no documentation on how to use this with the Dart js interop.

This is the object I am trying to create:

var index = lunr(function () {
    this.field('title', {boost: 10})
    this.field('body')
    this.ref('id')
  })

Currently this is all that I have.

JsObject index = new JsObject(context['lunr'], [()
    {

    }]);

How am I able to access this from an anonymous function?

Also where do I put the actual lunr.js? I am simply making a wrapper for it so I don't see any reason to have it in a HTML file unless necessary.

EDIT:

I have also tried:

Create a function to allow for using this keyword. (still not sure if this syntax is correct)

_f = new JsFunction.withThis( (t) {
    t.callMethod('field', ['title', {boost: 10}])
    t.callMethod('field', ['body'])
    t.callMethod('ref', ['id'])
  });

Then create a JsObject using that function:

JsObject index = new JsObject(context['lunr'], [_f]);

This will give me this error:

Exception: Unhandled exception: Closure call with mismatched arguments: function 'call'

NoSuchMethodError: incorrect number of arguments passed to method named 'call'
Receiver: Closure: (dynamic) => dynamic
Tried calling: call(Instance of 'JsObject', Instance of 'JsObject')
Found: call(t)
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)

Next I tried this:

JsObject index =new JsObject.fromBrowserObject(context['lunr']);

That gives me a different error: Exception: Illegal argument(s): object cannot be a num, string, bool, or null

This may be because I do not have a way to call the _f function when creating the JsObject that way.

how to enable --enable-experimental-mirrors in dart build?

My build of my projects are failing because they rely on mirrors and dart build out put tells me to use --enable-experimental-mirrors to try to use mirrors in dart2js code as it is. so if I run pub build --enable-experimental-mirrors all I get i

My build of my projects are failing because they rely on mirrors and dart build out put tells me to use --enable-experimental-mirrors to try to use mirrors in dart2js code as it is. so if I run pub build --enable-experimental-mirrors all I get is Could not find an option named "enable-experimental-mirrors". Any hints much appreciated.


pluto/1.3.2 - Ruby/2.0.0 (2014-11-13/x86_64-linux) on Sinatra/1.4.5 (production)