Skip to content

Instantly share code, notes, and snippets.

@chayanforyou
Created March 4, 2024 04:53
Show Gist options
  • Save chayanforyou/f66e8c57f41eb104122aaca554e6e891 to your computer and use it in GitHub Desktop.
Save chayanforyou/f66e8c57f41eb104122aaca554e6e891 to your computer and use it in GitHub Desktop.
Using an Isolate in Flutter
import 'dart:async';
import 'dart:isolate';
class CountdownTimer {
final receivePort = ReceivePort();
late Isolate _isolate;
void stop() {
receivePort.close();
_isolate.kill(priority: Isolate.immediate);
}
Future<void> start(Duration initialDuration) async {
Map map = {
'port': receivePort.sendPort,
'initial_duration': initialDuration,
};
_isolate = await Isolate.spawn(_entryPoint, map);
receivePort.sendPort.send(initialDuration);
}
static void _entryPoint(Map map) async {
Duration initialTime = map['initial_duration'];
SendPort port = map['port'];
Timer.periodic(
Duration(seconds: 1),
(timer) {
if (timer.tick == initialTime.inSeconds) {
timer.cancel();
port.send(timer.tick);
port.send('Timer finished');
} else {
port.send(timer.tick);
}
},
);
}
}
void main() {
final countdownTimer = CountdownTimer();
countdownTimer.start(Duration(seconds: 10));
countdownTimer.receivePort.listen((dynamic data) {
if (data is int) {
print('Timer tick: $data seconds');
} else if (data is String) {
print('Timer completed: $data');
countdownTimer.stop();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment