在构造函数中调用异步函数

时间:2020-04-15 20:21:43

标签: flutter asynchronous dart constructor

我有一个小部件,可通过对数据库的查询获得属性。因此,必须将此功能标记为异步,但是我不能在构造函数中调用它。有人知道如何解决这个问题吗?

class PositionWidget extends StatefulWidget {
   final String streetName;
   String date;
   List<Map> notification;
   final VoidCallback onDelete;

  PositionWidget({Key key, this.streetName, this.date,this.notification, @required this.onDelete}): super(key: key){
    this.notification = await DBHelper.instance.getNotification(this.streetName);
  }
}


Future<List<Map>> getNotification(String street) async {
    Database db = await DBHelper.instance.database;
    var res = await db.query(table, columns: [columnNot], where: '${DBHelper.columnName} = ?', whereArgs: [street]);
    return res;
}

3 个答案:

答案 0 :(得分:2)

您不能拥有async构造函数。使用FutureBuilder可能是最好的解决方案。

或者,您可以等待如下结果:

 PositionWidget({Key key, this.streetName, this.date,this.notification, @required this.onDelete}): super(key: key){
    DBHelper.instance.getNotification(this.streetName)
      .then((result){
         notification = result;
      });
  }

答案 1 :(得分:2)

initState() {
 myAsyncInit();
}

myAsyncInit() async {
 //do async stuff
}

答案 2 :(得分:1)

您无法在StatefulWidget的构造函数中进行此操作

您需要在initState()PositionWidgetState的{​​{1}})的State方法内进行呼叫

PositionWidget

您可能需要使用FutureBuilder或StreamBuilder来处理结果