如何在 initState 中等待异步

Faa*_*ass 9 flutter

我有一个异步函数,需要在有状态小部件的 initState 中调用,但我不能使用 await,因为 initState 不是异步的。

sendHealthDataasync因为它从 Health Api 获取一些信息,然后我需要将该信息发送到 HomeSubScreen,这是另一个StatefulWidget. 但是在创建 HomeSubScreen 时,该sendHealthData方法没有获取所有信息,因此如果我尝试将参数中的某个值发送到HomeSubScreen,则该值将为空。

我怎样才能做到这一点?

@override
  void initState() {
    super.initState();
    sendHealthData();
    _widgetOptions = <Widget>[
      HomeSubScreen(healthData),
    ];

  }
Run Code Online (Sandbox Code Playgroud)

更新:如果我添加了 then() 我会收到以下错误:

NoSuchMethodError: The method 'elementAt' was called on null.
Run Code Online (Sandbox Code Playgroud)

代码更新:

@override
      void initState() {
        super.initState();
        sendHealthData().then((response){
             _widgetOptions = <Widget>[
                 HomeSubScreen(healthData),
              ];
        });


      }
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 8

我给你一个大概的想法。

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

  function().then((int value) {
    // future is completed you can perform your task 
  });

  function2(); // or you can simply call the method if you don't want anything to do after future completes
}

Future<int> function() async {
  // do something here 
}

Future<int> function2() async {
  // do something here
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为 `setState(() {);` 应该在 `function().then((int value) { // future iscompleted you can run your task });` 里面,以便在结果后改变状态取来的。 (3认同)

Rav*_*mar 7

您还可以使用FutureBuilder

FutureBuilder<String>(
  future: getYourDataFromApi(), 
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Text('start widget');
      case ConnectionState.active:
      case ConnectionState.waiting:
        return Text('Awaiting result from api...');
      case ConnectionState.done:
        if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
        return Text('Result: ${snapshot.data}');
    }
    return null; // unreachable
  },
)
Run Code Online (Sandbox Code Playgroud)


cri*_*ant 6

您不能在 initState 中等待异步函数,但有一个小技巧是使用 Then 关键字在 future 完成后执行代码。

例如:

@override


void initState() {
    super.initState();
    sendHealthData().then((response){

      _widgetOptions = <Widget>[
        HomeSubScreen(response),
      ];

    });


  }
Run Code Online (Sandbox Code Playgroud)

并且该函数必须类似于:

Future sendHealthData() async{}
Run Code Online (Sandbox Code Playgroud)