Skip to content

Instantly share code, notes, and snippets.

@matanlurey
Created February 22, 2017 20:19
Show Gist options
  • Save matanlurey/4bf81f67ebce6fc03b24f8dc96b1f629 to your computer and use it in GitHub Desktop.
Save matanlurey/4bf81f67ebce6fc03b24f8dc96b1f629 to your computer and use it in GitHub Desktop.
Using the `Completer` API in Dart to make a JavaScript API more Dart idiomatic
@JS()
library fetch_contacts_interop;
import 'dart:async';
import 'package:func/func.dart';
import 'package:js/js.dart';
// Natively calls "fetch_contacts", but we can use typed Dart code while developing!
@JS('fetch_contacts')
external void _jsFetchContacts(String prefix, VoidFunc1<List<String>> callback);
// Here is our new function!
Future<List<String>> fetchContacts(String prefix) {
final completer = new Completer<List<String>>();
_jsFetchContacts(prefix, completer.complete);
return completer.future;
}
// Example use, including async/await!
main() async {
print('Contacts: ${await fetchContacts('A')}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment