Search code examples
dartdart2js

Passing typed array buffer to javascript from dart with js-interop


Trying to call a javascript method that required a typed array.

var arrayData = js.array(new Uint8Array.fromList(data.charCodes));

Using js.array does not proxy it the way I was expecting, how could I pass the typed array as a typed array to a javascript method in dart?


Solution

  • You can instantiate ArrayBuffer and Uint8Array javascript objects directly from Dart.

    If you need only a Uint8Array javascript object :

    js.scoped(() {
      final charCodes = "test".charCodes;
      final bufView = new js.Proxy(js.context.Uint8Array, js.array(charCodes));
    
      // do something with bufView
    });
    

    If you need an ArrayBuffer javascript object:

    js.scoped(() {
      final charCodes = "test".charCodes;
      final buf = new js.Proxy(js.context.ArrayBuffer, charCodes.length);
      final bufView = new js.Proxy(js.context.Uint8Array, buf)
        ..set(js.array(charCodes));
    
      // do something with buf
    });
    

    Basically, each time you need to use the new javascript operator, you have to use new js.Proxy(construtor,...).

    WARNING : Until a new version has landed containing the pull-request #34 of js-interop, you have to use the following dependency to run the above code snippet.

    dependencies:
      js:
        git: git://github.com/dart-lang/js-interop.git