【问题标题】:Call asynchronous function inside constructor在构造函数中调用异步函数
【发布时间】:2020-07-28 23:11:27
【问题描述】:

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

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;
}

【问题讨论】:

  • 我认为您应该根据您从 db 获取的方法使用 Future 或 Stream 构建器。

标签: flutter asynchronous dart constructor


【解决方案1】:

你不能有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;
      });
  }

【讨论】:

    【解决方案2】:
    initState() {
     myAsyncInit();
    }
    
    myAsyncInit() async {
     //do async stuff
    }
    

    【讨论】:

    • 虽然这段代码可能会解决问题,但一个好的答案还应该解释代码的什么以及它如何提供帮助。
    【解决方案3】:

    您不能在 StatefulWidget 的构造函数中执行此操作

    您需要在PositionWidgetStateinitState() 方法内拨打电话(PositionWidgetState

    class PositionWidgetState extends State<PositionWidget> {
      var res;
    
      @override
      void initState() {
        res = getNotification(widget.streetName);
      }
    

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

    【讨论】:

    • FutureBuilder 是一个与任何其他小部件一样的小部件。它正在监听 Future 并给出它的多种状态。请参阅api.flutter.dev/flutter/widgets/FutureBuilder-class.html 以获取更多信息
    • 当快照的ConnectionState不是"done"时我应该返回什么样的widget?
    • 你可以返回一个CircularProgressIndicator,或者你想要的任何其他小部件,比如一个文本Text("loading"),一个空的Container...
    猜你喜欢
    • 2018-09-16
    • 2014-05-27
    • 2017-04-14
    • 2012-08-05
    • 2013-12-27
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多