flutter_js
flutter_js copied to clipboard
Ability do async call from Dart to JS and from JS to Dart
I have created a simple add-on for async calls js-to-dart and dart-to-js.
You can use async sendMessage from one side and provide async handler from another.
From Dart side async sendMessage accept convertable to JSON data(provide toEncodable if you want pass own objects).
Usage example below. Full source code: js_bridge.dart.txt
example() async {
const exampleJs = '''
DartBridge.setHandler('TESTJS', async (args) => {
await new Promise(resolve => setTimeout(resolve, 2000));
return `JS code got args.name=\${args.name} and args.obj.num=\${args.obj.num}`;
});
const print = (message) => DartBridge.sendMessage('PRINT', message);
setTimeout(async () => {
print('Start async call to Dart');
const asyncCallToDartResult = await DartBridge.sendMessage('TESTDART', { some: 'object' });
print(`asyncCallToDartResult=\${asyncCallToDartResult}`);
}, 4000);
''';
final jsRuntime = getJavascriptRuntime();
final jsBridge = JsBridge(jsRuntime: jsRuntime, toEncodable: _toEncodable);
jsRuntime.evaluate(exampleJs);
jsBridge.setHandler('PRINT', (message) async {
_print('[JS] $message');
});
_print('Start async call to JS');
final asyncCallToJsResult = await jsBridge.sendMessage('TESTJS', {'name': 'value', 'obj': DataExample(str: 'some string', num: 54321)});
_print('asyncCallToJsResult=$asyncCallToJsResult');
jsBridge.setHandler('TESTDART', (message) async {
await Future.delayed(Duration(seconds: 2));
return 'Dart code got $message';
});
}
Output
flutter: [11:47:39:524] Start async call to JS
flutter: [11:47:41:540] asyncCallToJsResult=JS code got args.name=value and args.obj.num=54321
flutter: [11:47:43:525] [JS] Start async call to Dart
flutter: [11:47:45:531] [JS] asyncCallToDartResult=Dart code got {some: object}
ps. Thanks to author and all contributors for this lib.