How to spawn an async function in Flutter?

Issue

How an I spawn an Isolate blocking on an async function in Flutter?

I tried dart:cli‘s waitFor function, but it seems that dart:cli does not work together with Flutter.

Solution

There is no supported way to block on an async function.

You shouldn’t need an Isolate to block anyway. Each Isolate has its own event loop and can just await the Future returned by your asynchronous function before calling Isolate.exit. For example:

import 'dart:isolate';

void foo(SendPort p) async {
  for (var i = 0; i < 5; i += 1) {
    await Future.delayed(const Duration(seconds: 1));
    print('foo: $i');
  }

  Isolate.exit(p);
}

void main() async {
  var p = ReceivePort();
  await Isolate.spawn(foo, p.sendPort);
  print('Isolate spawned.');

  // Wait for the Isolate to complete.
  await p.first;
  print('Done');
}

which prints:

Isolate spawned.
foo: 0
foo: 1
foo: 2
foo: 3
foo: 4
Done

Answered By – jamesdlin

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *