【问题标题】:Flutter - Is there a way to load async metho on InitState? [duplicate]Flutter - 有没有办法在 InitState 中加载异步方法? [复制]
【发布时间】:2021-09-01 11:30:14
【问题描述】:

Flutter - 有没有办法在 InitState 上加载异步方法?我想在 iniState() 中调用异步方法;但它不起作用......

我正在寻找一种在 InitState 方法上加载异步数据的方法,在构建方法运行之前我需要一些数据。我需要执行构建方法直到 Stream 运行。

    @override
      void initState () {
        super.initState();

         //here i want to call async function
      }

【问题讨论】:

标签: flutter dart


【解决方案1】:

你可以试试下面的代码 sn-p。

方法 1:创建一个异步方法并从您的 initState() 方法中调用它,如下所示:

 @override
   void initState() {
   super.initState();
   asyncMethod();
   }

   void asyncMethod() async {
   await asyncCall1();
   await asyncCall2();
   // ....
  }

【讨论】:

    【解决方案2】:

    您可以创建一个单独的方法并在 initState() 中调用。此外,您可以使用 WidgetBinding 来调用这样的函数。

    void initState() {
        WidgetsBinding.instance.addPostFrameCallback((_)  => {
          your_method();
        // TODO: implement initState
        super.initState();
      }
    

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 2021-08-17
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2017-12-23
      相关资源
      最近更新 更多