Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 697
Tarun Mishra Avatar asked Jul 09 '20 20:07

Tarun Mishra


People also ask

Is await blocking in Flutter?

Like it or not, when you use await inside a function, that function is now in danger of blocking the main thread, so it must be marked as async.

How does await work in Flutter?

You can think of await as a syntactic sugar of then . It makes asynchronous operations look synchronous. await will wait for a future to complete before executing the subsequence statement. This makes asynchronous operations appear to be synchronous.

How does async await work in Flutter?

Execution flow with async and await An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.

What is async* in Dart?

The Future class, part of dart:async, is used for getting the result of a computation after an asynchronous task has completed. This Future value is then used to do something after the computation finishes. Once the read operation is completed, the execution control is transferred within "then()".


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.

like image 150
Rémi Rousselet Avatar answered Sep 26 '22 01:09

Rémi Rousselet