Async/Await/then in Dart/Flutter

前端 未结 4 995
傲寒
傲寒 2020-12-03 05:45

I have a flutter application where I am using the SQFLITE plugin to fetch data from SQLite DB. Here I am facing a weird problem. As per my understanding, we use either asyn

4条回答
  •  眼角桃花
    2020-12-03 06:31

    in simple words:

    await is meant to interrupt the process flow until the async method has finished. then however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.

    In your example, you cannot achieve what you want when you use then because the code is not 'waiting' and the return statement is processed and thus returns an empty list.

    When you add the await, you explicitey say: 'don't go further until my Future is completed (the then part).

    You could write your code as follow to achieve the same result only with await:

    Future> getExpensesByFundId(int fundId) async {
        Database db = await database;
    
        List expenseList = List();
    
        List> expList = await db.query(expTable,where: '$expTable.$expFundId = $fundId');
        expList.forEach((Map expMap) {
            expenseList.add(Expense.fromMap(expMap));
        });
    
        return expenseList;
    }
    

    You could also chose to use only the then part, but you need to ensure to call getExpensesByFundId properly afterward:

    Future> getExpensesByFundId(int fundId) async {
        Database db = await database;
    
        List expenseList = List();
    
        return db.query(expTable,where: '$expTable.$expFundId = $fundId')
            .then((List> expList){
          expList.forEach((Map expMap){
            expenseList.add(Expense.fromMap(expMap));
          });
        });
    }
    
    // call either with an await
    List list = await getExpensesByFundId(1);
    // or with a then (knowing that this will not interrupt the process flow and process the next instruction
    getExpensesByFundId(1).then((List l) { /*...*/ });
    

提交回复
热议问题