I want to convert sync method to run as asynchronous
Simple example :
Future<void> increment() async {
for (var i = 0; i < 100000000; i++) {
_counter++;
}
}
When I use this code with flutter the app will freeze, because the code content is running as sync, so now I want to know how can I make this code run as async?
i tried to add Future.delayed
as following :
Future<void> increment() async {
for (var i = 0; i < 100000000; i++) {
_counter++;
await Future.delayed(const Duration(microseconds: 1));
}
}
But in some scenarios, it will takes too long time!
Is there a better solution?
2
Answers
Use Isolates in Dart for heavy calculations
There is compute constant in Flutter api for top-level and static functions who manage with Isolates by themselves.
Look into this page Concurrency in Dart
Paste the following code into a test.dart file, and see how you can create an async method from scratch using isolates.
Also try this code and notice the difference (which result will be printed first) when we do not use the async/await when calling the asynchronous method: