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

パッケージ詳細v7.4.4

squadron

Dart / Flutter のマルチスレッドおよびワーカースレッドプール。CPUバウンドおよび重いI/OタスクをIsolateまたはWeb Workerスレッドにオフロードします。

AndroidiOSWebmacOSWindowsLinux
30日間ダウンロード
3.1万
いいね数
216
Pub ポイント
160

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

flutter pub add squadron

パッケージ概要

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

Squadronは、IsolateとWeb Workerプールを介してマルチスレッド処理を可能にするDart/Flutterパッケージであり、CPU集約型および重いI/O操作をメインスレッドからオフロードできます。Android、iOS、Web、macOS、Windows、Linuxなど、さまざまなプラットフォームでの並列実行を簡素化します。ネイティブプラットフォームではIsolate、WebではWeb Workerを利用することで、アプリの応答性とパフォーマンスが向上します。このパッケージは、ワーカースレッドの管理やタスクの配布を簡単に行えるAPIを提供しています。

用途

  • CPU集約的な計算をオフロードする
  • 大規模なファイルI/O操作の処理
  • 集中作業中のUIの応答性の向上
  • バックグラウンドでのデータ処理を実行中
  • メインスレッドをブロックせずに長時間実行されるアルゴリズムを実行する

主な機能

  • 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

ソースリポジトリ

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

データはまだありません。