在 workmanager flutter 中监听函数的更改

Listen to changes from a function in workmanager flutter

提问人:Shreyansh Sharma 提问时间:11/17/2023 更新时间:11/17/2023 访问量:17

问:

我正在执行在我的 flutter 应用程序中上传视频的后台任务。我想在我的UI上显示完成进度。

在实现 workmanager 之前,我使用了 valuenotifier,它正在更新我的 ui。但是在使用 workmanager 之后,情况就不一样了。

我的代码:

@pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+
void callbackDispatcher() {
  print("Running callback dispatcher");
  Workmanager().executeTask((task, inputData) async {
    if(inputData!=null) {
      print("Task started");
      await uploadVideos(uploadVideoData: UploadVideoData.fromJson(inputData));
      print("Task completed");
    }
    else {
      //TODO:
    }
    return Future.value(true);
  });
}



await Workmanager().initialize(
      callbackDispatcher, // The top level function, aka callbackDispatcher
      isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
  );
  String uniqueId = '${uploadVideoData.rId}_${uploadVideoData.pId}_${uploadVideoData.groupId}';
  await Workmanager().registerOneOffTask(uniqueId, uniqueId, inputData: uploadVideoData.toJson());

该函数是一个顶级 main 函数,在 main.dart 中声明。callbackDispatcher

在uploadVideos函数中,我更新了值,如下所示:

.......
uploadPercent.value = 0;
.......
....... 
    await uploadAsset(
            rid: uploadVideoData?.rId ?? 0,
            grpId: uploadVideoData?.groupId ?? 0,
            pId: uploadVideoData?.pId ?? 0,
            asset: File(compressedVideoPath),
            onChanged: (percent) {
              if(uploadVideoData?.fromGallery==true) {
                uploadPercent.value = ((percent * 100) / 2) + 50;
              }
              else {
                uploadPercent.value = percent*100;
              }
              debugPrint('Uploading percent is: $percent');
            });
.......
.......
....... 

上传百分比在 main 的顶层中是这样定义的:

ValueNotifier<double> uploadPercent = ValueNotifier(0);

此外,在函数之前和之后,我正在更新提供程序变量中的一些值。例如:uploadAsset

videoUploadingProvider.currentUpdate = uniqueId;

此 videoUploadingProvider 也定义在顶层,在main.dart.

VideoProvider videoUploadingProvider = VideoProvider();

当我直接使用 时,这些都在工作,而不是调用它。uploadVideosWorkmanager().executeTask

如何解决这个问题?

Flutter Dart 后台服务

评论


答: 暂无答案