gpt4 book ai didi

flutter - 如何在 Flutter 的 FutureBuilder 中调用 setState

转载 作者:行者123 更新时间:2023-12-05 08:17:59 25 4
gpt4 key购买 nike

我正在尝试根据 FutureBuilder 收到的结果设置状态,看起来这是不可能的,因为 FutureBuild 仍在构建中,有什么想法吗?
错误:

The following assertion was thrown building FutureBuilder<String>(dirty, state: _FutureBuilderState<String>#db9f1):
setState() or markNeedsBuild() called during build.

This StatefulBuilder widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: StatefulBuilder

我的代码:

FutureBuilder<String>(
future: fetchIdPlayer(idPlayer, bouquet),
builder: (context, snapid) {
if (!snapid.hasData)
return Container(
height: mobileHeight * 0.05,
child: Center(
child: CircularProgressIndicator(),
),
);
else if (snapid.data == "Error_ID") {
setState(() {
have_ID = true;
resultName = "رقم تعريف اللاعب خاطئ";
});
}
})

最佳答案

您可以通过安排 setState 在下一帧而不是在构建期间执行来解决您遇到的错误。

  else if (snapid.data == "Error_ID") {    
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
///This schedules the callback to be executed in the next frame
/// thus avoiding calling setState during build

setState(() {
have_ID = true;
resultName = "رقم تعريف اللاعب خاطئ";
});
});
...

关于flutter - 如何在 Flutter 的 FutureBuilder 中调用 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69151812/

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