我有一个小部件,可通过对数据库的查询获得属性。因此,必须将此功能标记为异步,但是我不能在构造函数中调用它。有人知道如何解决这个问题吗?
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;
}
答案 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来处理结果