flutter visitChildElements()在构建期间被调用



我正在尝试创建一个下载功能,从url下载文件到手机存储,我做了一个小部件来显示,如果下载开始,也使用getx obs显示进度计数器

final ApiServiceController uController = Get.put(ApiServiceController());
downloading(String fileUrl, String fileName) async {
Dio dio = Dio();
fToast("Downloading... $fileName", pop);
try {
var dir = await downloadDirectory();
uController.isDwd.value = true;
await dio.download(fileUrl, "${dir.path}/$fileName",
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
uController.dwdP.value = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
fToast("Downloaded", pop);
} catch (e) {
print(e);
}
uController.isDwd.value = false;
print("Download completed");
}

小部件显示

Stack(children: [
///.. Container widget here,
Obx(() {
return uController.isDwd.value
? loading(context, uController.dwdP.value)
: SizedBox(height: 0);
})
])

但是当我点击下载按钮开始下载时它会抛出错误

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Obx(has builder, dirty, state: _ObxState#291e4):
visitChildElements() called during build.
The BuildContext.visitChildElements() method can't be called during build because the child list is still being updated at that point, so the children might not be constructed yet, or might be old children that are going to be replaced.
The relevant error-causing widget was
Obx

错误显示在屏幕上,直到下载完成。我看到使用这个将修复它

WidgetsBinding.instance.addPostFrameCallback((_) {
// executes after build
});

但是我不知道在这种情况下如何使用它。请有办法解决这个问题,如果你需要更多的解释或信息,请告诉我

你的代码看起来不错。我认为你应该在GitHub上创建一个关于GetX的问题。

在我的情况下,我在控制器上错误地改变了2次可观察变量。在小部件构建方法

我认为这个问题是由在子部件内使用obs变量引起的,它的父部件也包含相同或以某种方式相同的obs变量,或者在子部件中有一个与父部件相关的状态操作。你最好提供更多的UI代码,以使清楚的子部件的细节,但我的猜测是,你正在做一些操作的上下文,你给了加载小部件,该操作导致UI的构建和变化的上下文中,如果没有请提供更详细的代码。

在我的情况下,我改变了可观察变量2次错误一次在on select &在小部件构建方法中。

然后我评论了其中一个,它开始工作了。

这可能也适用于您.....试试。

谢谢。

最新更新