Sub topic 2
Using compute in Flutter
This chapter assumes you know async and await, Futures, and basic widgets. It covers how Flutter's compute function moves work off the UI isolate, what data can cross between isolates, how to avoid capturing too much in a closure, and how errors come back to the caller.
Using compute in Flutter
compute is a Flutter helper that runs a top-level function in a separate isolate and returns the result as a Future. It takes the function and one argument.
import 'package:flutter/foundation.dart';
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
Future<int> computeFib() {
return compute(fib, 35);
}What you can send, and what gets copied
Isolates do not share memory. Arguments and results are copied across. Numbers, strings, lists, maps, and records of these types are safe to send. Objects with open files, sockets, or platform handles cannot be sent.
Avoiding accidental captures in closures
A closure that uses an instance field captures this, which can pull in more data than you expect. Copy the field into a local variable first.
import 'dart:isolate';
int sumList(List<int> values) => values.fold(0, (a, b) => a + b);
class Report {
Report(this.values);
final List<int> values;
Future<int> total() {
final data = values; // Capture only the list.
return Isolate.run(() => sumList(data));
}
}Handling errors from an isolate
If the work throws, the Future completes with that error. Wrap the await in try and catch, as you would for any other async call.
Future<void> safeFib() async {
try {
final value = await compute(fib, 35);
print('Result: $value');
} catch (e) {
print('Worker failed: $e');
}
}Exercise
Exercise
If the function passed to compute throws an error, where can you catch it?
Show answer
In the calling code. Wrap the await of compute in try and catch, because the returned Future completes with the error.