如何在不使用onPressed的情况下在Flutter中进行异步函数调用?

时间:2020-08-04 21:00:38

标签: flutter asynchronous dart

这可能是一个初学者的问题,但是我想给一个类变量分配一个Future函数。我只知道您可以在onPressed按钮上使用异步功能,但是如何在Widget构建甚至初始化时运行这些异步功能?

1 个答案:

答案 0 :(得分:0)

无论何时尝试构建依赖于future的小部件,您都可能想使用FutureBuilder小部件。

FutureBuilder有其自己的生成方法,可以根据需要为future的结果提供一个初始值。


class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: name_Of_Your_Future
        initialData: value, //initial value for the future(ie: until it resolves)
        builder: (BuildContext context, AsyncSnapshot snapshot) {
         
          //...some UI building logic here...
   
          //snapshot.data contains the result of your future,
          //once it is resolved

  }
}