相关疑难解决方法(0)

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");
    }
  }
Run Code Online (Sandbox Code Playgroud)
  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 …

multithreading async-await dart flutter

6
推荐指数
1
解决办法
1169
查看次数

异步/等待/然后在Dart / Flutter中

我有一个Flutter应用程序,正在使用SQFLITE插件从Sqlite数据库中获取数据。在这里,我面临一个奇怪的问题。根据我的理解,我们使用async / await或then()函数进行异步编程。在这里,我有一个db.query()方法,该方法正在执行一些SQL查询以从db获取数据。在此函数获取数据之后,我们将在.then()函数中进行一些进一步的处理。但是,用这种方法我遇到了一些问题。从我调用此getExpensesByFundId(int fundId)函数的位置来看,它似乎无法正确获取数据。它应该返回Future>对象,然后在数据可用时将其转换为List。但是当我打电话时它不起作用。

但是,我只是对其进行了一些试验,并在db.query()函数之前添加了“ await”关键字,并且以某种方式使其开始可以正常工作。您能否解释为什么添加await关键字可以解决此问题?我以为使用.then()函数时,我们不需要使用await关键字。

这是我的代码:

Future<List<Expense>> getExpensesByFundId(int fundId) async {
    Database db = await database;

    List<Expense> expenseList = List();

   // The await in the below line is what I'm talking about

    await db.query(expTable,where: '$expTable.$expFundId = $fundId')
        .then((List<Map<String,dynamic>> expList){
      expList.forEach((Map<String, dynamic> expMap){
        expenseList.add(Expense.fromMap(expMap));
      });
    });
    return expenseList;
  }
Run Code Online (Sandbox Code Playgroud)

asynchronous dart flutter

3
推荐指数
1
解决办法
7068
查看次数