Tar*_*hra 6 multithreading async-await dart 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");
}
}
Run Code Online (Sandbox Code Playgroud)
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???
等待调用是非阻塞的。它的工作方式是,虽然 Dart 是单线程的,但一些 Dart 代码将它们的实现委托给 Dart VM。
文件读取或 HTTP 请求之类的事情在 Dart 之外(由浏览器或在 C++ 中)在不同的线程中执行。
因此,虽然 Dart 是单线程的,但它仍然能够在不锁定 UI 的情况下同时执行多个任务。
| 归档时间: |
|
| 查看次数: |
1169 次 |
| 最近记录: |