I am trying to create a download functionality which downloads files from url in to phone storage and i made a widget to display if the download starts and also the progress counter to be displayed using 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");
}
Widget to display
Stack(children: [
///.. Container widget here,
Obx(() {
return uController.isDwd.value
? loading(context, uController.dwdP.value)
: SizedBox(height: 0);
})
])
but whenever i click the download button to start download it throws the error
════════ 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
And the error displays on the screen until the download is done. I saw that using this will fix it
WidgetsBinding.instance.addPostFrameCallback((_) {
// executes after build
});
but i don't know how to use it in this case. Please is there a way to fix this and if you need more explanation or info please tell me