Skip to content

prefer_compute_over_isolate_run

v0.4.0 Warning Fix Code Quality

Flags uses of Isolate.run() from dart:isolate, which is not supported on the web platform. Flutter’s compute() function from package:flutter/foundation.dart provides the same background execution capability while working across all platforms including web.

Isolate.run() throws at runtime on web targets, because browsers do not support Dart isolates. compute() gives the same background execution and works on mobile, desktop and web, with no platform-specific branching.

See also: Flutter - compute() | Dart - Isolate.run()

Parsing a large payload off the UI thread — correct everywhere except in the browser:

import 'dart:isolate';
class ReportParser {
Future<int> parse(String csv) async {
return Isolate.run(() => _countRows(csv));
}
static int _countRows(String csv) => csv.split('\n').length;
}

compute() takes a one-argument callback and its message, so the closure gains a parameter. The quick fix does this rewrite for you and adds the foundation.dart import:

import 'package:flutter/foundation.dart';
class ReportParser {
Future<int> parse(String csv) async {
return compute((_) => _countRows(csv), null);
}
static int _countRows(String csv) => csv.split('\n').length;
}

Better still, pass the payload as the message so nothing is captured by the closure:

import 'package:flutter/foundation.dart';
class ReportParser {
Future<int> parse(String csv) => compute(_countRows, csv);
static int _countRows(String csv) => csv.split('\n').length;
}

What the quick fix does to each callback shape

Section titled “What the quick fix does to each callback shape”
You wrote The fix produces
Isolate.run(() => work()) compute((_) => work(), null)
Isolate.run(() async => work()) compute((_) async => work(), null)
Isolate.run(() { ... }) compute((_) { ... }, null)
Isolate.run(work) compute((_) => work(), null)

Only Isolate.run is reported, and only when Isolate resolves to dart:isolate. A class of your own named Isolate is left alone.

Other isolate APIs are not covered. Isolate.spawn, ReceivePort and friends have no compute equivalent and are never reported.

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_compute_over_isolate_run: true

To turn it off again:

many_lints.yaml
rules:
prefer_compute_over_isolate_run: false

To keep the rule on but skip certain paths, use per-rule exclude.