Skip to content

HelloWorld

d-markey edited this page Jun 23, 2023 · 6 revisions

You're now ready to write your first Squadron service. It can be as simple as:

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

part 'hello_world.worker.g.dart';

@SquadronService()
class HelloWorld {
    @SquadronMethod()
    Future<String> hello([String? name]) async {
        name = name?.trim();
        if (name == null || name.isEmpty) {
            return 'Hello, World!';
        } else {
            return 'Hello, $name!';
        }
    }
}

Use build_runner to generate the worker code:

dart run build_runner build

You're now ready to execute the service in a separate thread and call it from your application's main thread:

// file main.dart
import 'hello_world.dart';

void main() async {
    final worker = HelloWorldWorker(); // instantiate a worker thread for HelloWorld
    await worker.start(); // optional - Squadron will automatically start workers as necessary
    print(await worker.hello());
    print(await worker.hello('Mary'));
    print(await worker.hello('John'));
    worker.stop(); // required to terminate the worker and stop the program
}

Squadron logo

Squadron - Multithreading and worker pools in Dart.

Offload CPU-bound and long running tasks and give your mobile and Web apps some air!

Pub Package Dart Platforms Flutter Platforms

License Null Safety Dart Style Pub Points Likes Popularity

Clone this wiki locally