首页 > 解决方案 > 如何在 Global Snackbar 中制作进度指示器(下载百分比)?

问题描述

我正在尝试实现一个全局 downloadFile() 函数和一个全局小吃栏,以便即使在导航到另一个小部件后,小吃栏和下载也能继续工作。问题是下载进度(下载百分比)根本没有更新。这是 CustomSnackBar

          class CustomSnackBar {
        static bool isDownloading = false;
        static String progress = "0%";
        CustomSnackBar._();
        static Future<void> downloadFile(
            BuildContext context, String fileUrl, fileName) async {
          Dio dio = Dio();
        
          isDownloading = true;
          try {
            var dir = await getApplicationDocumentsDirectory();
            await dio
                .download(fileUrl, "${dir.path}/notifications_files/$fileName.pdf",
                    onReceiveProgress: (rec, total) {
              progress = '${((rec / total) * 100).toStringAsFixed(0)} %';
              buildErrorSnackbar(context, "empty");
            });
            isDownloading = false;
          } catch (e) {
            print(e);
          }
        }

        static buildErrorSnackbar(BuildContext context, String message) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              duration: const Duration(days: 100),
              backgroundColor: kPrimaryColor,
              content: snacBarDownloading(progress),
              action: SnackBarAction(
                textColor: kWhiteColor,
                label: 'Dismiss',
                onPressed: () {},
              ),
            ),
          );
        }
      }

      Widget snacBarDownloading(String progress) {
        // print(progress);
        return Row(children: [
          const SizedBox(
              width: 25,
              height: 25,
              child: CircularProgressIndicator(color: kWhiteColor)),
          const SizedBox(
            width: 10,
          ),
          Text("Downloading $progress ...",
              style: const TextStyle(color: kWhiteColor))
        ]);
      }

这就是我调用下载功能的地方

  return InkWell(
      onLongPress: () {
        if (!isDownloading &&
            widget.notificationList[index].fileUrl != null &&
            widget.notificationList[index].fileUrl!.isNotEmpty) {
          CustomSnackBar.downloadFile(
              context,
              widget.notificationList[index].fileUrl!,
              widget.notificationList[index].serviceId!);
        }
      },

标签: fluttersnackbar

解决方案


推荐阅读