Isolates

Isolates won't work on dart pad , you should use a local environment.

Spawning isolates

import 'dart:isolate';

void main() {
// isolates
  Isolate.spawn(entryFunction, "This is a message from the main isolate");
  print("Inside Main Isolate");
}

void entryFunction(message) {
  print(message);
}

A single isolate running it's own event loop

Each isolate has their own segment of memory

The "entryFunction" has to be a top level function(i.e. not any function inside class or interface or something like that) or a static function

Working with ports

import 'dart:isolate';

void main() async {
  ReceivePort rport = ReceivePort();
  rport.listen((data) {
    if (data is int) {
      print(data);
    } else {
      print(data);
      rport.close();
    }
  });

// isolates
  Isolate i1 = await Isolate.spawn(entryFunction, rport.sendPort);
}

void entryFunction(SendPort sport) {
  for (int i = 0; i < 1000000; i++) {
    sport.send(i);
  }

  sport.send("Finished");
}

Passing objects into isolates

import 'dart:isolate';

void main() async {
  ReceivePort rport = ReceivePort();
  rport.listen((data) {
    if (data is int) {
      print(data);
    } else {
      print(data);
      rport.close();
    }
  });

  InitMessage initmessage = InitMessage(1000, rport.sendPort);
// isolates
  Isolate i1 = await Isolate.spawn(entryFunction, initmessage);
}

void entryFunction(InitMessage initmessage) {
  for (int i = 0; i <= initmessage.increment; i++) {
    initmessage.sport.send(i);
  }

  initmessage.sport.send("Finished");
}

class InitMessage {
  int increment;
  SendPort sport;

  InitMessage(this.increment, this.sport);
}

Creating a Two way connection between isolates

import 'dart:isolate';

void main() async {
  ReceivePort rport = ReceivePort();
  rport.listen((data) {
    if (data is int) {
      print(data);
    } else if (data is SendPort) {
      data.send("Test");
    } else {
      print(data);
    }
  });

  InitMessage initmessage = InitMessage(1000, rport.sendPort);
// isolates
  Isolate i1 = await Isolate.spawn(entryFunction, initmessage);
}

void entryFunction(InitMessage initmessage) {
  for (int i = 0; i <= initmessage.increment; i++) {
    initmessage.sport.send(i);
  }

  initmessage.sport.send("Finished");

  ReceivePort rrport = ReceivePort();

  initmessage.sport.send(rrport.sendPort);

  rrport.listen((data) {
    print(data);
  });
}

class InitMessage {
  int increment;
  SendPort sport;

  InitMessage(this.increment, this.sport);
}

In Flutter you can use "compute" method which handles a lot the things for you and it's much easier to implement

This section gives you a basic idea about how to work with isolates . But you can imagine how complicated it will get if you need to manage multiple isolates . You should write a separate class that will help deal with this efficiently . Or use some high level package from pub.dev

Last updated