带有BLOC和存储库模式的Flutter工作管理器

wj8zmpe1  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(139)

我使用了blocrepository pattern。需要根据计划在后台执行代码,为此我使用了workmanager。问题是workmanager是在单独的方法中执行的,该方法是在main方法之外初始化的,并且它不了解上下文或下面的代码(如MyApp

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    
    //How i can access bloc or repository from here?
    return Future.value(true);
  });
}

void main() async {

Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager().registerPeriodicTask('uniqueName', 'taskName',
      constraints: Constraints(
        networkType: NetworkType.connected,
        requiresBatteryNotLow: true,
      ),
      frequency: const Duration(minutes: 5));

}

Workmanager是在main方法的最开始初始化的,在runApp MyApp之前,它没有上下文,我的存储库和块甚至还没有创建,我不知道如何从工作管理器访问块。

8yoxcaq7

8yoxcaq71#

您可以在注册定期任务时将repository和bloc的示例作为输入数据传递,然后在callbackDispatcher方法中访问它们:

final Repository _repository = Repository();
final Bloc _bloc = Bloc();

void main() async {
  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager().registerPeriodicTask('uniqueName', 'taskName',
      inputData: {'repository': _repository, 'bloc': _bloc},
      constraints: Constraints(
        networkType: NetworkType.connected,
        requiresBatteryNotLow: true,
      ),
      frequency: const Duration(minutes: 5));
  runApp(MyApp());
}

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    final Repository repository = inputData['repository'];
    final Bloc bloc = inputData['bloc'];
    // Use repository and bloc as needed
    return Future.value(true);
  });
}

您还可以为存储库和块类使用单例模式:

class Repository {
  static final Repository _singleton = Repository._internal();
  factory Repository() {
    return _singleton;
  }

  Repository._internal();
  // Repository methods
}

class Bloc {
  static final Bloc _singleton = Bloc._internal();
  factory Bloc() {
    return _singleton;
  }

  Bloc._internal();
  // Bloc methods
}

void main() async {
  Repository();
  Bloc();
  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager().registerPeriodicTask('uniqueName', 'taskName',
      constraints: Constraints(
        networkType: NetworkType.connected,
        requiresBatteryNotLow: true,
      ),
      frequency: const Duration(minutes: 5));
  runApp(MyApp());
}

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    final Repository repository = Repository();
    final Bloc bloc = Bloc();
    // Use repository and bloc as needed
    return Future.value(true);
  });
}

相关问题