Why in this code, await is not blocking ui in flutter

Viewed 2312

In the default example app whenever you create new fultter project I just added the following code.

  initState() {
    super.initState();
    loop();
  }

  loop() async {
    while (true) {
      await Future.delayed(Duration(milliseconds: 10));
      print("count now:$_counter");
    }
  }
  1. Why is the app UI is not getting blocked? I am able to click + button and the counter increases smoothly. Even if I change the delay to 10 sec, the UI is resposive. Is the loop() runnning in different thread?but I know dart is single thread. How is it possible?

  2. Where the loop function is running?

  3. Can I use this technique to run background task for example checking id my sqflite table rows are synced with cloud etc???

1 Answers

Await calls are non-blocking. The way this works is, while Dart is single-threaded, some Dart code delegate their implementation to the Dart VM.

Things like file reads or HTTP requests are performed outside of Dart (either by the browser or in c++), in a different thread.

So while Dart is single-threaded, it is still able to perform multiple tasks simultaneously without locking the UI.

Related