0

我使用 workmanager 每 15 分钟在后台检索用户的位置。当位置获取失败时,我会收到一条错误通知,如图所示。我想知道如何防止通知出现在失败的情况下。

    void callbackDispatcher() {
  Workmanager.executeTask((taskName, inputData) async {
    if (taskName == FETCH_USER_POSITION_IN_BACKGROUND_TASK_NAME) {
      // TODO: Find a better way to get user position, maybe with ServiceLocator or even better with BLoC
      final dataSource = GeolocatorDataSource();
      final remoteDataSource = FirestoreRemoteDataSource(
        firebaseFirestore: FirebaseFirestore.instance,
      );
      final repository = GeolocationRepository(
        geolocationDataSource: dataSource,
        remoteDataSource: remoteDataSource,
      );

      final positionEither = await repository.getUserPosition();
      positionEither.fold((failure) async {
        print('failure: $failure');
      }, (position) async {
        print('position = $position');
        final storePositionEither =
            await repository.storeUserPosition(position, inputData['uid']);
        storePositionEither.fold((failure) async {
          print('failure: $failure');
        }, (isStored) async {
          print("Position has been successfully stored in background!");
        });
      });
    }

    return Future.value(true);
  });
}



void _initializeWorkManagerWhenAuthenticated(String userId) {
    bool isProduction = bool.fromEnvironment('dart.vm.product');

    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: !isProduction,
    );

    Workmanager.registerPeriodicTask(
      FETCH_USER_POSITION_IN_BACKGROUND_TASK_ID,
      FETCH_USER_POSITION_IN_BACKGROUND_TASK_NAME,
      frequency: Duration(minutes: 15),
      existingWorkPolicy: ExistingWorkPolicy.keep,
      inputData: {
        'userId': userId,
      },
    );
  }

在此处输入图像描述

4

1 回答 1

0

您是否检查过运行时是否出现通知isInDebugMode: false

参见:https ://github.com/fluttercommunity/flutter_workmanager/blob/ea274c33b60ef1a4e29bdd392a477f67466dc25d/lib/src/workmanager.dart#L90

于 2021-03-07T19:49:37.407 回答