Planet Dart

Updated Tuesday, 06 January 2015 17:01
{}
Dart Questions ( Feed )
Tuesday, 06 January 2015
How can we get the real size of the screen in inches with Dart?
  • window.innerHeight
  • window.innerWidth

gives you the size of the window in "CSS pixel" not in real ones.

To develop a responsive application we need to know the real size of the screen to adapt the behavior of the application.

  • window.innerHeight
  • window.innerWidth

gives you the size of the window in "CSS pixel" not in real ones.

To develop a responsive application we need to know the real size of the screen to adapt the behavior of the application.

The solution in the Javascript world doesn't seem good enough

How can we do that properly in Dart?

What is the main purpose of List.single property?

Some days ago, I noticed that Dart's List class has the single property. Then, I read an official API document, and understood how this property works. This mean I know that List.single works as follows:

print(['a'].single);     

Some days ago, I noticed that Dart's List class has the single property. Then, I read an official API document, and understood how this property works. This mean I know that List.single works as follows:

print(['a'].single);     // outputs 'a'
print(['a', 'b'].single) // throws StateError

But I cannot find any practical use case of the single property. Childish codes showed above make no sense in actual programming, of course.

What is the purpose of the property? Why does this property throw an Exception if a List contains two or more elements? Why is it not a boolean property which stands for whether a List has only single element? How do Dart Language developers think it is useful to include List.single in the core API?

If you have any knowledge about this, I would appreciate it very much if you give me a hand.

Dart Errors in multi-level asynchronous code

Consider the following code

import 'dart:async';

Future main() async {
  try {
    print("trying");
    await doSomething();
    print("success");
  } catch (e) {
    print("caught");
  }
}

Future<int> doSomething() async {
  await doSomethingEl

Consider the following code

import 'dart:async';

Future main() async {
  try {
    print("trying");
    await doSomething();
    print("success");
  } catch (e) {
    print("caught");
  }
}

Future<int> doSomething() async {
  await doSomethingElse();
  return 5;
}

Future<int> doSomethingElse() async {
  throw new Exception();
}

When run, the exception thrown in doSomethingElse() is caught up in main(), and everything works as expected. But, say the person who wrote the doSomething() method didn't realize that doSomethingElse() was asynchronous, and instead wrote the follow (note the missing await).

Future<int> doSomething() async {
  doSomethingElse();
  return 5;
}

Now the exception isn't caught at all. Rather, the output now looks like this:

trying
success
Unhandled exception:
Uncaught Error: Exception
Stack Trace:
#0      doSomethingElse.<doSomethingElse_async_body> (file:///C:/code/test.dart:19:7)
#1      Future.Future.<anonymous closure> (dart:async/future.dart:118)
<snip>

What's happening is that doSomething() is returning immediately, and then sometime later, in another context, doSomethingElse() is throwing its error, stopping all execution immediately. I know that an answer to this might be "Well, don't do that then." but I'm considering cases where I might not have control over the methods I'm calling (say if they are part of a library).

This situation leads to a couple of related questions:

  • As the author of main(), is there any way I can be certain that my call to doSomething() won't end with an unhandled exception? Or am I dependent on the author of doSomething() to make sure all possible exceptions are handled or propagated to the returned Future? Is there a way to attach some sort of global error handler that can catch errors from abandoned Futures?
  • As the author of doSomething(), if I don't want to wait on doSomethingElse() (say it writes to a log for example, so I neither need the output nor do I need to worry about handling errors). Is there anything I can do to prevent errors in doSomethingElse() from halting the program other than wrapping every call of it a try/catch block (which can be cumbersome an easily overlooked)?
  • As the author of doSomethingElse(), is there some pattern I can use which allows me to throw Exceptions in a way that callers who wait for the Future to complete can handle that Exception themselves whereas callers that don't wait for the Future don't have to worry about catching the Exception? My best thought in that regard is to return a special object rather than throwing an Exception, but that adds a lot of extra cruft and makes the method much harder use.

Note: I'm using async/await syntax here, but the question should be equally relevant for a more strictly Future based construction (where you return a new Future in doSomething() instead of .then()ing off the one from doSomethingElse()

{}
Dart Questions ( Feed )
Monday, 05 January 2015
Why is Dart's Datetime.parse not a factory constructor?

Dart's Datetime class has a number of named constructors, but DateTime.parse() is not one of them. Instead, DateTime.parse() is a static method which returns a DateTime. To me, it makes sense as a constructor (since you are generating a new Date

Dart's Datetime class has a number of named constructors, but DateTime.parse() is not one of them. Instead, DateTime.parse() is a static method which returns a DateTime. To me, it makes sense as a constructor (since you are generating a new DateTime object in a manner not too different from the Datetime.utc() constructor).

Theories I've come up with are to mirror the fact that int.parse is not a constructor or to allow easier chaining (you don't need to use the cascade operator with a static method). But maybe there is another reason that I'm not thinking of. Does anyone know why they didn't make it a named constructor?

How to register factory of part in Dart

I have a lot of part of library. But all of the same type (extends Part)

part1.dart

part of Parts;
class Part1 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part1(varOfSomeClass + 1); });

part2.dart

I have a lot of part of library. But all of the same type (extends Part)

part1.dart

part of Parts;
class Part1 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part1(varOfSomeClass + 1); });

part2.dart

part of Parts;
class Part2 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part2(varOfSomeClass - 1); });

parts.dart

library Parts;
part "Part1.dart";
part "Part2.dart";
List<Function> parts = new List<Function>();
class Parts {
  getPart(int index) {
    if (parts.contains(index)) {
      return parts[index](someVarOfThisClass);
    }
  }
}

OUTPUT: error: unexpected token 'parts'

How to get all included factories without create instance all the Part classes?

For example need to do:

BMW.dart

part of Auto;
class BMW {
    String color;
    BMW(this.color);
}
list.add((color){
    return new BMW(color);
});

Lada.dart

part of Auto;
class Lada {
    List<int> color;
}
list.add((color){
    var auto = new Lada();
    auto.color = hex2rgb(color);
    return auto;
});

Auto.dart

library Auto;
class Auto {
    getByIndex(int index) {
        if (list.contains(index)) {
            return list[index](color);
        }
        return null;
    }
}
get filed/getter name using a variable that points to the same reference

I have 2 classes

class A {
  B b = new B();
  B _b2 = new B();
  B get b2 =>_b2;
}

class B{

}

I wanted to write a method with the following signature

String getFieldName(Object parentContext, Object context)


I have 2 classes

class A {
  B b = new B();
  B _b2 = new B();
  B get b2 =>_b2;
}

class B{

}

I wanted to write a method with the following signature

String getFieldName(Object parentContext, Object context)

where parentContext parameter is a class instance that contains a getter or a field that points to the same reference as the context parameter, example

  var aInstance = new A();
  var referenceToB = aInstance.b;
  var referenceToB2 = aInstance.b2;

  print(getFieldName(aInstance, referenceToB));
  print(getFieldName(aInstance, referenceToB2));

should print

b
b2

My ugly guess is

String getFieldName(Object parentContext, Object context) {
  InstanceMirror parentContextInstanceMirror = reflect(parentContext);
  List<Symbol> parentContextFieldSymbols = new List<Symbol>();

  parentContextInstanceMirror.type.declarations.forEach((k, v) {
    if (!v.isPrivate) {
      if (v is VariableMirror) {
        parentContextFieldSymbols.add(k);
      }
      if(v is MethodMirror){
        var mm = v as MethodMirror;
        if(mm.isGetter)
          parentContextFieldSymbols.add(k);
      }
    }
  });

  for (final fieldSymbol in parentContextFieldSymbols) {
    if (parentContextInstanceMirror.getField(fieldSymbol).reflectee == context) {
      return MirrorSystem.getName(fieldSymbol);
    }
  }

  throw 'NOT FOUND';
}

Could some one please give me a better way, what I do is I reflect all fields and getters and compare the reference to the context parameter.

Cast a variable as a function/method pointer in Dart? (Delegate?)

Say I have a Map type that stores functions/methods inside of it, like so:

Map triggerHandler = {
  'x' : (t) => hello(t)
};

Now, what I want to do next is to declare that the Type of these Map values are to be functions.

I

Say I have a Map type that stores functions/methods inside of it, like so:

Map triggerHandler = {
  'x' : (t) => hello(t)
};

Now, what I want to do next is to declare that the Type of these Map values are to be functions.

I can always do this:

Map<String, dynamic> triggerHandler = {
  'x' : (t) => hello(t)
};

But this doesn't help stop programmers from putting in non-functions into the Map values. 'x' could then be a String, or an Integer.

The reason I want to do this is because I have a function that needs to only accept Maps with functions as the values. Calling the array key of 'x' is done by triggerHandlerx when it is a function, rather than triggerHandler[x]. I haven't tested if this causes an error to occur or not, but this doesn't seem semantically correct to me.

It would seem that the most logical way to do this would be to set the Type for the value as a function. Such as giving a Map a type casted value of 'delegate':

Map<String, delegate> triggerHandler = { // Note, this won't work
  'x' : (t) => hello(t)
};

What is the correct way to do this in Dart? (If there is a way) Thank you.

pdfmake generate a pdf using dart

I am trying to generate a pdf file in dart which all but impossible with the current resources available.

However it was mentioned to me that I may be able to do it via JsObject. So, using pdfmake in JS the code looks like:

var docDefinition = {

I am trying to generate a pdf file in dart which all but impossible with the current resources available.

However it was mentioned to me that I may be able to do it via JsObject. So, using pdfmake in JS the code looks like:

var docDefinition = { content: 'This is an sample PDF printed with pdfMake' };
pdfMake.createPdf(docDefinition).open();

which works by creating a popup window with the content.

So, to try to make this work in Dart I commented out the createPdf line and in Dart wrote:

var pdf = context['pdfMake'];
var docDefinition = context['docDefinition'];
pdf.callMethod('createPdf', ['docDefinition']).callMethod('open', []);

which opens the popup window but immediately closes it again with no apparent error anywhere.

My question is, simply, is this actually possible to do or am I flogging a dead horse?

{}
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.


pluto/1.3.2 - Ruby/2.0.0 (2014-11-13/x86_64-linux) on Rails/4.2.0 (production)