isolate_flutter 4.0.0
isolate_flutter: ^4.0.0 copied to clipboard
IsolateFlutter provides a way to launch 'dart:isolate' library in Flutter (iOS and Android).
IsolateFlutter #
IsolateFlutter is a useful package for you who want to make and manage Isolate. It is based on dart:isolate so it only support iOS and Android.
It's like compute(): Spawn an isolate, run callback on that isolate, passing it message, and (eventually) return the value returned by callback. But it not top-level constant so you can create multiple Isolates at the same time.
Requirements #
Flutter >=3.35.0, Dart ^3.9.0. Verified against Flutter 3.44.
Installation #
dependencies:
isolate_flutter: ^4.0.0
import 'package:isolate_flutter/isolate_flutter.dart';
Usage #
Create and start an isolate #
final _value = await IsolateFlutter.createAndStart(_testFunction, 'Hello World');
print(_value);
Create and manager an isolate (not run immediately) #
-
Create an isolate. It returns
nullif the isolate could not be created:final IsolateFlutter? _isolateFlutter = await IsolateFlutter.create(_testFunction, 'Hello World'); -
Start and get the value returned by _testFunction
final _value = await _isolateFlutter?.start(); print(_value); -
Pause a running isolate
_isolateFlutter?.pause(); -
Resume a paused isolate
_isolateFlutter?.resume(); -
Stop and dispose a an isolate
_isolateFlutter?.stop();stop()kills the isolate, so work that is still in flight is abandoned. TheFuturereturned bystart()never completes in that case.
Reading the state #
_isolateFlutter?.isRunning;
_isolateFlutter?.isPaused;
_isolateFlutter?.isStopped; // also true before the isolate has ever started
Example test function #
The callback must be a top-level function or a static method — it cannot be a closure or an instance method, because it has to be sent to another isolate.
Future<String> _testFunction(String message) async {
Timer.periodic(const Duration(seconds: 1), (timer) => print('$message - ${timer.tick}'));
await Future<void>.delayed(const Duration(seconds: 30));
return '_testFunction finish';
}
Errors #
If the callback throws, the error and its stack trace are forwarded to the
calling isolate, so start() / createAndStart() rethrow the original error:
try {
await IsolateFlutter.createAndStart(_testFunction, 'Hello World');
} on StateError catch (e) {
print(e);
}
Author #
IsolateFlutter is developed by Thong Dang. You can contact me at thongdn.it@gmail.com
If you like my project, you can support me
or star (like) for it.
Thank you! ❤️