Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

firebase

dart

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

like image 567
Andy Burnett Avatar asked Feb 15 '13 22:02

Andy Burnett


2 Answers

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

like image 70
Alexandre Ardhuin Avatar answered Sep 20 '22 01:09

Alexandre Ardhuin


There's now a wrapper for the firebase.js library in Dart here: https://github.com/firebase/firebase-dart/ (also available on pub). It uses dart:js as discussed in this thread, so inclusion of firebase.js is still required!

like image 22
Anant Avatar answered Sep 21 '22 01:09

Anant