flutter_qjs 0.0.5 flutter_qjs: ^0.0.5 copied to clipboard
This plugin is a simple js engine for flutter using the `quickjs` project. Plugin currently supports Windows, Linux, and Android.
flutter_qjs #
A quickjs engine for flutter.
Feature #
This plugin is a simple js engine for flutter using the quickjs
project. Plugin currently supports Windows, Linux, and Android.
Each FlutterJs
object creates a new thread that runs a simple js loop.
ES6 module with import
function is supported and can manage in dart with setModuleHandler
.
A global async function dart
is presented to invoke dart function, and Promise
is supported so that you can use await
or then
to get external result from dart
. Data convertion between dart and js are implemented as follow:
dart | js |
---|---|
Bool | boolean |
Int | number |
Double | number |
String | string |
Uint8List/Int32List/Int64List | ArrayBuffer |
Float64List | number[] |
List | Array |
Map | Object |
Closure(List) => Future | function(....args) |
notice:
-
All the
Uint8List/Int32List/Int64List
sent from dart will be converted toArrayBuffer
without marked the size of elements, and theArrayBuffer
will be converted toUint8List
. -
function
can only sent from js to dart and all the arguments will be packed in a dartList
object.
Getting Started #
- Create a
FlutterJs
object. Make sure calldestroy
to terminate thread and release memory when you don't need it.
FlutterJs engine = FlutterJs();
// do something ...
await engine.destroy();
engine = null;
- Call
setMethodHandler
to implementsdart
interaction. For example, you can useDio
to implements http in js:
await engine.setMethodHandler((String method, List arg) async {
switch (method) {
case "http":
Response response = await Dio().get(arg[0]);
return response.data;
default:
return JsMethodHandlerNotImplement();
}
});
and in javascript, call dart
function to get data:
dart("http", "http://example.com/");
- Call
setModuleHandler
to resolve js module. For example, you can use assets files as module:
await engine.setModuleHandler((String module) async {
return await rootBundle.loadString("js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js");
});
and in javascript, call import
function to get module:
import("hello").then(({default: greet}) => greet("world"));
- Use
evaluate
to run js script, and try-catch is needed to capture js exception.
try {
print(await engine.evaluate(code ?? '', "<eval>"));
} catch (e) {
print(e.toString());
}
This example contains a complete demonstration on how to use this plugin.