gpt4 book ai didi

flutter - 如何在已经获得的 future 中实现FutureBuilder

转载 作者:行者123 更新时间:2023-12-03 03:24:47 26 4
gpt4 key购买 nike

根据文档,我对如何实现Flutter的FutureBuilder感到有些困惑。我这里有一个可以运行的Future Builder,唯一的问题是每次运行构建方法时都会使用Future:

FutureBuilder(
future: DBProvider.db.getUser(),
builder: (_, userData) {
switch (userData.connectionState) {
case ConnectionState.none:
return Container();
case ConnectionState.waiting:
return Container();
case ConnectionState.active:
case ConnectionState.done:
newUser = userData.data;
return ListView(
shrinkWrap: true,
children: <Widget>[
... // Lot's of things
],
);
}
return null;
},
),

然后,我意识到文档的这一部分的重要性,它说 future 必须“早日获得”,这样就不会发生此问题:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.



这是我的问题的出处,我理解这些词在说什么,但是根据代码的确切含​​义来表达代码?

我是否简单地创建一个函数并在initState中调用它,就像这样:
@override
void initState() {
super.initState();
_getUser();
}

_getUser() async {
newUser = await DBProvider.db.getUser();
}

在这种情况下,FutureBuilder的 future 论点会怎样?还是这完全不对?

最佳答案

是的,您的方向正确。解决此问题的最简单方法是在状态中存储Future变量。在initState中进行API调用并存储Future。然后,您可以将此Future传递给FutureBuilder。

像这样:

class MyWidget extends StatefulWidget {
State createState() {
return MyState();
}
}

class MyState extends State<MyWidget> {
Future userFuture;
void initState() {
super.initState();
// Note here we are not awaiting the user, but rather storing
// the future in the variable
userFuture = DBProvider.db.getUser();
}

Widget build(BuildContext context) {
return FutureBuilder(
future: userFuture,
builder: (BuildContext, snapshot) {
...
}
);
}
}

关于flutter - 如何在已经获得的 future 中实现FutureBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com