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