搜尋套件、儲存庫與 APP 分類

套件詳情v0.3.7

flutter_qjs

此外掛程式是使用 `quickjs` 項目為 Flutter 提供的簡單 JS 引擎。此外掛程式目前支援除 Web 以外的所有平台!

近 30 天下載
194
喜歡數
31
Pub 分數
60

安裝套件

flutter pub add flutter_qjs

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

flutter_qjs 是一個 Flutter 插件,整合了 QuickJS JavaScript 引擎,讓 Dart 應用程式能夠原生執行 JavaScript 程式碼。它支援除了 web 以外的所有主要平台,非常適合需要輕量級嵌入式腳本的場景。該插件提供簡單的 API,可評估 JS 表達式、呼叫函數,並在 Dart 與 JavaScript 之間交換資料。基於高效率的 QuickJS 項目建構,確保快速執行且開銷極小。這使其適用於動態邏輯、設定腳本,或在不重新編譯的情況下擴展應用功能。

適用情境

  • 在應用程式中執行動態腳本
  • 嵌入 JavaScript 邏輯
  • 在執行時擴展應用行為
  • 透過腳本配置應用功能
  • 與舊版 JS 程式碼互動

主要特色

  • 輕量級 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 項

原始碼儲存庫

使用此套件的專案