我正在尝试创建一个下载功能,它可以将文件从url下载到电话存储中,如果下载开始,我还制作了一个小部件来显示,以及使用getx 显示的进度计数器。
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");
}
Widget显示
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
});
但我不知道在这个案子里该怎么用。请有办法解决这个问题,如果您需要更多的解释或信息,请告诉我。
发布于 2022-03-25 06:35:14
我认为这个问题是由在子小部件中使用一个obs变量引起的,它的父小部件也包含相同或相同的obs变量,或者在子小部件中有一个状态操作,这与父部件的操作有关。您最好提供更多的UI代码,以明确子部件的细节,但我的猜测是,您正在对加载小部件的上下文进行一些操作,并且操作会导致UI在上下文中的构建和更改,如果不是,请提供更详细的代码。
https://stackoverflow.com/questions/69410762
复制相似问题