パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細v0.3.7

flutter_qjs

このプラグインは、`quickjs` プロジェクトを使用して Flutter 用のシンプルな JS エンジンです。現在、Web を除くすべてのプラットフォームをサポートしています!

30日間ダウンロード
194
いいね数
31
Pub ポイント
60

パッケージをインストール

flutter pub add flutter_qjs

パッケージ概要

公開情報に基づく選定ガイドです。参考としてご利用ください。

flutter_qjs は、QuickJS JavaScript エンジンを統合する Flutter プラグインであり、Dart アプリケーションがネイティブに JavaScript コードを実行できるようにします。Web を除くすべての主要プラットフォームをサポートしており、軽量で埋め込み可能なスクリプトが必要なシナリオに最適です。このプラグインは、JS 式の評価、関数の呼び出し、Dart と JavaScript の間でのデータ交換を可能にするシンプルな API を提供します。高性能な QuickJS プロジェクトに基づいており、最小限のオーバーヘッドで高速な実行を保証します。これにより、動的論理、設定スクリプト、または再コンパイルなしにアプリ機能を拡張する場合に適しています。

用途

  • アプリケーションでダイナミックスクリプトを実行する
  • JavaScript ロジックの埋め込み
  • 実行時におけるアプリ動作の拡張
  • スクリプトを介してアプリ機能を設定する
  • レガシージェイエスコードとの連携

主な機能

  • 軽量な QuickJS エンジン
  • クロスプラットフォーム(ウェブ以外)
  • Dart-JS相互運用性
  • スクリプト評価のためのシンプルな API
  • 低メモリ使用量での高速実行

適している対象

  • 動的スクリプトが必要なアプリ
  • 論理処理にJSを使用する開発者
  • 埋め込みエンジンを必要とするプラグイン
  • スクリプタブルコンポーネントを使用したプロトタイピング
  • ウェブ以外のモバイルおよびデスクトップアプリケーション

注意事項

  • Web プラットフォームでは利用できません
  • QuickJS 固有の JavaScript 機能に限定
  • 注意深いエラー処理が必要です
  • アプリのサイズがわずかに増加する可能性があります
  • 現代の ES モジュールに対応していません

元の README

関連するソースリポジトリの README 原文のスナップショットです。最新の内容はリポジトリをご覧ください。

flutter_qjs

Pub Test

English | 中文

This plugin is a simple js engine for flutter using the quickjs project with dart:ffi. Plugin currently supports all the platforms except web!

Getting Started

Basic usage

Firstly, create a FlutterQjs object, then call dispatch to establish event loop:

final engine = FlutterQjs(
  stackSize: 1024 * 1024, // change stack size here.
);
engine.dispatch();

Use evaluate method to run js script, it runs synchronously, you can use await to resolve Promise:

try {
  print(engine.evaluate(code ?? ''));
} catch (e) {
  print(e.toString());
}

Method close can destroy quickjs runtime that can be recreated again if you call evaluate. Parameter port should be close to stop dispatch loop when you do not need it. Reference leak exception will be thrown since v0.3.3

try {
  engine.port.close(); // stop dispatch loop
  engine.close();      // close engine
} on JSError catch(e) { 
  print(e);            // catch reference leak exception
}
engine = null;

Data conversion between dart and js are implemented as follow:

dart js
Bool boolean
Int number
Double number
String string
Uint8List ArrayBuffer
List Array
Map Object
Function(arg1, arg2, ..., {thisVal})
JSInvokable.invoke([arg1, arg2, ...], thisVal)
function.call(thisVal, arg1, arg2, ...)
Future Promise
JSError Error
Object DartObject

Use Modules

ES6 module with import function is supported and can be managed in dart with moduleHandler:

final engine = FlutterQjs(
  moduleHandler: (String module) {
    if(module == "hello")
      return "export default (name) => `hello \${name}!`;";
    throw Exception("Module Not found");
  },
);

then in JavaScript, import function is used to get modules:

import("hello").then(({default: greet}) => greet("world"));

notice: Module handler should be called only once for each module name. To reset the module cache, call FlutterQjs.close then evaluate again.

To use async function in module handler, try run on isolate thread

Run on Isolate Thread

Create a IsolateQjs object, pass handlers to resolving modules. Async function such as rootBundle.loadString can be used now to get modules:

final engine = IsolateQjs(
  moduleHandler: (String module) async {
    return await rootBundle.loadString(
        "js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js");
  },
);
// not need engine.dispatch();

Same as run on main thread, use evaluate to run js script. In isolate, everything returns asynchronously, use await to get the result:

try {
  print(await engine.evaluate(code ?? ''));
} catch (e) {
  print(e.toString());
}

Method close can destroy isolate thread that will be recreated again if you call evaluate.

Use Dart Function (Breaking change in v0.3.0)

Js script returning function will be converted to JSInvokable. It does not extend Function, use invoke method to invoke it:

(func as JSInvokable).invoke([arg1, arg2], thisVal);

notice: evaluation returning JSInvokable may cause reference leak. You should manually call free to release JS reference.

(obj as JSRef).free();
// or JSRef.freeRecursive(obj);

Arguments passed into JSInvokable will be freed automatically. Use dup to keep the reference.

(obj as JSRef).dup();
// or JSRef.dupRecursive(obj);

Since v0.3.0, you can pass a function to JSInvokable arguments, and channel function is no longer included by default. You can use js function to set dart object globally. For example, use Dio to implement http in qjs:

final setToGlobalObject = await engine.evaluate("(key, val) => { this[key] = val; }");
await setToGlobalObject.invoke(["http", (String url) {
  return Dio().get(url).then((response) => response.data);
}]);
setToGlobalObject.free();

In isolate, top level function passed in JSInvokable will be invoked in isolate thread. Use IsolateFunction to pass a instant function:

await setToGlobalObject.invoke([
  "http",
  IsolateFunction((String url) {
    return Dio().get(url).then((response) => response.data);
  }),
]);

カテゴリー

依存関係

依存関係一覧 1 件

ソースリポジトリ

このパッケージを使用しているプロジェクト