Has anyone tried using the Firebase javascript library from within Dart?

dart, firebase

Solution

You can use any Javascript library through the js package.

For Firebase you have to :

- add the js package to your `pubspec.yaml`

dependencies:
  js: any

- add the the following `<script>` to your html page :

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script type="application/dart" src="youDartCode.dart"></script>
<script src="packages/browser/dart.js"></script>
<script src="packages/browser/interop.js"></script> 

- use Firebase Javascript SDK through js package. Something like :

import 'package:js/js.dart' as js;

void main() {
  final myDataRef = new js.Proxy(js.context.Firebase,
      'https://xxx.firebaseio-demo.com/');
  myDataRef.on('child_added', (snapshot, String previousChildName) {
    final message = snapshot.val();
    print("${message.name} : ${message.text}");
  });
  myDataRef.push(js.map({"name": 'myName', "text": 'js interop rocks'}));
}

The above Dart code is the equivalent of the following JavaScript code :

var myDataRef = new Firebase('https://xxx.firebaseio-demo.com/');
myDataRef.on('child_added', function(snapshot, previousChildName) {
  var message = snapshot.val();
  console.log(message.name + " : " + message.text);
}));
myDataRef.push({name: 'myName', text: 'js interop rocks'});

Basically :

when you have to instantiate a Javascript object, use `new js.Proxy(js.context.MyJavascriptObjectName, arg1, arg2, arg3))`,

when you have to provide a Javascript anonymous object, use `js.map({'attr1', value1}, {'attr2', value2})`.

Problem

The Firebase key-value store looks intriguing, and would be fun to use with Dart's HTML framework. They offer a JavaScript library for reading/writing to their model. Has anyone tried using it with Dart? My plan (based on very little Dart knowledge) is to: - Include their library in my html - Load the js.dart package - instantiate a model through js.dart - read and write through model. Does that seem like the right approach? Or, is there a much better way of doing it? Thanks

Original source