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

套件詳情v7.4.4

squadron

Dart / Flutter 的多執行緒與工作執行緒池,用於將 CPU 負載型及繁重的 I/O 任務卸載至 Isolate 或 Web Worker 執行緒。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
3.1萬
喜歡數
216
Pub 分數
160

安裝套件

flutter pub add squadron

套件介紹

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

Squadron 是一個 Dart/Flutter 套件,透過隔離區與 Web Worker 池實現多執行緒,讓 CPU 負載與繁重的 I/O 操作能從主執行緒卸載。它簡化了在 Android、iOS、Web、macOS、Windows 及 Linux 等平台上的平行執行。透過在原生平台使用隔離區,在 Web 上使用 Web Worker,Squadron 提升了應用程式回應性與效能。該套件提供簡單易用的 API 來管理工作執行緒與處理任務分配。

適用情境

  • 卸載CPU密集型計算
  • 處理大檔案 I/O 操作
  • 在密集任務期間提高使用者介面的響應性
  • 正在執行背景資料處理
  • 在不阻塞主執行緒的情況下執行長時間運行的演算法

主要特色

  • 支援 Isolate 和 Web Worker 池
  • 跨平台相容性
  • 簡單的任務提交 API
  • 自動工作管理
  • 內建錯誤處理
  • 執行緒安全通訊

適合對象

  • 需要高效率後台處理的開發人員
  • 具有複雜數據轉換的應用程式
  • 媒體或影像處理應用
  • 即時資料分析工具
  • 在高負載情況下需要回應式UI的應用程式

使用建議

  • 需要理解隔離和併發
  • 使用大量工作進程時可能會增加記憶體使用量
  • Web 支援受限於瀏覽器功能
  • 不適用於輕量級任務
  • 需要在多執行緒之間進行仔細的狀態管理

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

Squadron logo

Squadron - Multithreading and worker pools in Dart

Offload CPU-bound and long running tasks and give your apps some air!
Works everywhere: Desktop, Server, Mobile, and Browser (JS & WASM).

Quick Start • Why Squadron? • Wiki Documentation • Samples

Pub Package Dart Platforms Flutter Platforms

Pub Points Likes Downloads License Null Safety Dart Style

Last Commit Dart Workflow Code Lines Code Coverage

Online Web Test Console

🚀 Why Squadron?

Dart is single-threaded by nature. While Isolate.run() is great for one-off tasks, it creates overhead for frequent operations, and is not available on browser platforms.

Squadron provides:

  • 🔄 Persistent Worker Pools: Keep workers alive and ready to process tasks instantly.
  • 🌐 Seamless Web Support: Uniform API for Isolates (Native) and Web Workers (JS/Wasm).
  • 🛡️ Type Safety: Automatic code generation ensures your thread boundaries are type-safe.
  • 🚫 Cancellation: Gracefully cancel long-running tasks.
  • 📡 Streaming: Native support for Stream return types from workers.

🏗️ Architecture

sequenceDiagram
    autonumber
    
    participant App as Main App (UI)
    box rgb(40, 100, 200, 0.1) Squadron / Generated Code
        participant Pool as HelloWorldWorkerPool/Worker
    end
    box rgb(0, 150, 0, 0.1) Background Thread
        participant Service as User Service
    end
    
    App->>Pool: worker.hello('Squadron')
    Pool->>Service: Assign Task (Marshaled)
    activate Service
    Note over Service: Executing on background Isolate/Web Worker
    Service-->>Pool: Return Result (Unmarshaled)
    deactivate Service
    Pool-->>App: Future<String> Result

📖 Table of Contents


1. Getting Started

Add Squadron to your dependencies and squadron_builder to your dev dependencies:

dependencies:
  squadron: ^7.4.0

dev_dependencies:
  build_runner:
  squadron_builder: ^9.0.0

Run dart pub get to install.

2. Implementing a Service

Create a class with the logic you want to run in the background. Use @SquadronService and @SquadronMethod annotations.

// file: hello_world.dart
import 'dart:async';
import 'package:squadron/squadron.dart';

import 'hello_world.activator.g.dart';
part 'hello_world.worker.g.dart';

@SquadronService(baseUrl: '~/workers', targetPlatform: TargetPlatform.all)
base class HelloWorld {
  @SquadronMethod()
  FutureOr<String> hello([String? name]) {
    name = name?.trim() ?? 'World';
    return 'Hello, $name!';
  }
}

3. Generating Workers

Squadron uses code generation to handle the boilerplate of thread communication. Run the following command:

dart run build_runner build

This creates HelloWorldWorker and HelloWorldWorkerPool. These classes implement the same interface as your service but proxy calls to background threads.

4. Running your Worker

In your application, instantiate the worker and use it like a normal service.

[!IMPORTANT]
Always stop your workers. Failure to call worker.stop() will keep your program running indefinitely.

import 'hello_world.dart';

void main() async {
  final worker = HelloWorldWorker();
  try {
    // Squadron starts the worker automatically on the first call
    final message = await worker.hello('Squadron');
    print(message);
  } finally {
    worker.stop(); // Clean up the background thread
  }
}

🌍 Web Support (JS & Wasm)

Squadron is designed for a "write once, run anywhere" experience. When targeting the web, you must compile your worker entry points:

# Compile to JavaScript
dart compile js ".\src\lib\hello_world.web.g.dart" -o "..\web\workers\hello_world.web.g.dart.js"
# Compile to Web Assembly
dart compile wasm ".\src\lib\hello_world.web.g.dart" -o "..\web\workers\hello_world.web.g.dart.wasm"

Squadron will automatically detect the runtime environment and choose the correct implementation.


🛠️ Advanced Concepts

Data Transfer & Marshaling

Because workers run in separate memory spaces, data must be serialized ("marshaled") to cross thread boundaries. While base types (Strings, Numbers, Lists, Maps) are handled automatically, custom objects require a SquadronMarshaler.

📖 Learn more: Data Transfer and Types & Marshaling Wiki

Exception Handling

Exceptions thrown in a worker are caught, serialized, and re-thrown on the caller's side, preserving the stack trace and error information where possible.

📖 Learn more: Exception Management Wiki

Logging

Debugging background workers can be tricky. Squadron provides mechanisms to forward log messages from workers back to the main thread's debugger or console.

📖 Learn more: Observability and Logging Wiki


Special Thanks


View the Full Wiki • API Reference

所屬分類

依賴

依賴清單 5 項

  • cancelation_token^1.1.0
  • logger^2.1.0
  • meta^1.11.0
  • using^1.0.0
  • web^1.1.0

原始碼儲存庫

使用此套件的專案

暫無相關資料。