【发布时间】:2021-11-23 09:21:34
【问题描述】:
我正在尝试创建一个下载功能,将文件从 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
});
但我不知道在这种情况下如何使用它。请问有没有办法解决这个问题,如果您需要更多解释或信息,请告诉我
【问题讨论】:
标签: flutter dart flutter-getx