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
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})
.
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!
I got the error message "Breaking on exception: ReferenceError: ReceivePortSync is not defined" when Dart got to here.
js.scoped (() {
});
An additional line of code is needed to use Firebase with Dart. Add the line "packages/browser/interop.js"
<script type="application/dart" src="ScrollViewDemo.dart"></script>
<script src="packages/browser/dart.js"></script>
<script src="packages/browser/interop.js"></script>
<script src='https://cdn.firebase.com/v0/firebase.js'></script>
----------------- Edit Aug 15 ----------
js.scoped is no longer needed in the newer version of interopt.js