Skip to content

Getting Started

d-markey edited this page Jan 22, 2026 · 4 revisions

This guide will walk you through setting up a basic Squadron project.


1. Add Dependencies

Update your pubspec.yaml to include squadron in your dependencies and squadron_builder (plus build_runner) in your dev_dependencies.

dependencies:
  squadron: ^7.4.0

dev_dependencies:
  build_runner:
  squadron_builder: ^9.0.0

Run dart pub get to install the packages.

2. Implement a Service

Create a simple service class. This class contains the logic you want to run in a background thread.

  1. Annotate the class with @SquadronService().
  2. Annotate public methods you want to expose with @SquadronMethod().
  3. Ensure methods return Future, FutureOr, or Stream.

lib/hello_world.dart:

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

import 'hello_world.activator.g.dart'; // generated later
part 'hello_world.worker.g.dart';      // generated later

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

3. Generate Code

Run the build runner to generate the worker plumbing:

dart run build_runner build

This will generate several files:

  • hello_world.worker.g.dart
  • hello_world.activator.g.dart
  • Other files for platform-specific implementations.

4. Use the Worker

In your main application code, you can now use HelloWorldWorker. It has the same interface as your service but runs inside a separate thread.

lib/main.dart:

import 'hello_world.dart';

void main() async {
  // Create the worker
  final worker = HelloWorldWorker();
  
  try {
    // Call the method. Squadron handles the thread startup automatically.
    final message = await worker.hello('Squadron User');
    print(message);
  } finally {
    // ALWAYS stop the worker when done to free resources
    worker.stop();
  }
}

Next Step: Learn more about Installation and Generation.

Clone this wiki locally