skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    import 'dart:io';
    import 'dart:isolate';
    
    void main() async {
      // Read some data.
      final result = await Isolate.run(_readAndParseDart);
      print("Called the async function");
    }
    
    String _readAndParseDart() {
      final fileData = File("test.dart").readAsStringSync();
      print('Finished the asynchronous code');
    
      return fileData;
    }
    

    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:

    import 'dart:io';
    import 'dart:isolate';
        
        void main() {
          // Read some data.
          final result = Isolate.run(_readAndParseDart);
          print("Called the async function");
        }
        
        String _readAndParseDart() {
          final fileData = File("test.dart").readAsStringSync();
          print('Finished the asynchronous code');
        
          return fileData;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search