搜索插件、代码仓与 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 项

源码仓库

使用此插件的项目