作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据文档,我对如何实现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;
},
),
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.
@override
void initState() {
super.initState();
_getUser();
}
_getUser() async {
newUser = await DBProvider.db.getUser();
}
最佳答案
是的,您的方向正确。解决此问题的最简单方法是在状态中存储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/
我是一名优秀的程序员,十分优秀!