【问题标题】:How to make an async function call in Flutter without onPressed?如何在没有 onPressed 的情况下在 Flutter 中进行异步函数调用?
【发布时间】:2020-11-25 00:39:30
【问题描述】:

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

【问题讨论】:

  • 您可以随心所欲地使用异步函数。我建议研究框架和 Dart 的基础知识。

标签: flutter asynchronous dart


【解决方案1】:

当您尝试构建依赖于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

  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2013-02-20
    相关资源
    最近更新 更多