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");
}
}
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?
Where the loop function is running?
Can I use this technique to run background task for example checking id my sqflite table rows are synced with cloud etc???
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.
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.
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.
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()".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With