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

我正在尝试根据 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 = "رقم تعريف اللاعب خاطئ";
      });
    });
...

https://stackoverflow.com/questions/69151812/

相关文章:

c++ - 未初始化的引用是否为零初始化和未初始化的标量默认初始化?

android - 无法查询属性 'namespace' 的值

ios - 是否有修改器可以更改 SwiftUI Picker 的标签颜色?

javascript - Vue 3 defineEmits 打破了 defineProps 类型

angular - TS2322 : Type 'HTMLDivElement' is not as

regex - 如何在 perl regex 替换命令中使用 unicode 字符?

python - 正则表达式:在前瞻断言的最后一场比赛之后直到前瞻断言的第一场比赛之后查找文本

c++ - 从 std `vector` 库创建的 `` 和从 : `STL vec

python - 无法让 VS Code 将参数从 launch.json 传递给 Python

python - 检查文件夹,如果不存在则创建它