9

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???

Tarun Mishra
  • 363
  • 4
  • 10

1 Answers1

12

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.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • The case is different with native android by the way. Could you help explain the difference in what's happening in both the cases? – Harsha Jun 27 '22 at 06:10
  • Isn't it related to the nature of the Event Loop rather than another thread or handling request outside Dart? – Ensei Tankado Dec 17 '22 at 22:02