Created
March 4, 2024 04:53
-
-
Save chayanforyou/f66e8c57f41eb104122aaca554e6e891 to your computer and use it in GitHub Desktop.
Using an Isolate in Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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