【问题标题】:Can't use Geolocator inside Workmanager's task in Flutter无法在 Flutter 的 Workmanager 任务中使用 Geolocator
【发布时间】:2022-06-16 22:02:41
【问题描述】:
我正在尝试在 Workmanager 的任务中使用 Geolocator.getCurrentLocation 或 Geolocator.checkPermission()。这两个调用都引发了相同的异常:
MissingPluginException(No implementation found for method getCurrentPosition on channel flutter.baseflow.com/geolocator) - 代表getCurrentLocation。
MissingPluginException(No implementation found for method checkPermission on channel flutter.baseflow.com/geolocator) 用于 checkPermission 方法。
这是代码示例
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) async {
await Geolocator.checkPermission();
await Geolocator.getCurrentPosition();
});
}
Geolocator 的 GitHub 存储库中打开的问题很少,但没有答案。
关于如何解决这个问题的任何想法?
【问题讨论】:
标签:
flutter
geolocation
flutter-workmanager
geolocator
【解决方案1】:
所以,我找到了当前问题的解决方案。我所要做的就是将geolocator_android lib 的版本从^3.1.6 替换为3.1.5。
由于某些原因,3.1.6 版无法正常工作。
geolocator: ^8.2.0
geolocator_android: 3.1.5
【解决方案2】:
问题在于geolocator_android 3.1.6 版的默认方法通道实现已被平台特定实现所取代。然而,由于任务是在没有 Flutter 引擎的情况下在单独的隔离中运行的,因此平台特定的实现(在本例中为 geolocator_android)未向平台接口(@987654325@)注册,从而导致MissingPluginException。
要使用 3.1.6 或更高版本,请确保在运行 executeTask 时注册特定于平台的实现。
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
if (defaultTargetPlatform == TargetPlatform.android) {
GeolocatorAndroid.registerWith();
} else if (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS) {
GeolocatorApple.registerWith();
} else if (defaultTargetPlatform == TargetPlatform.linux) {
GeolocatorLinux.registerWith();
}
await Geolocator.checkPermission();
await Geolocator.getCurrentPosition();
});
}
或者,如果您运行的是 Flutter 2.11+,您可以使用新的 DartPluginRegistrant.ensureInitialized() 方法来确保所有包都正确注册:
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
DartPluginRegistrant.ensureInitialized();
await Geolocator.checkPermission();
await Geolocator.getCurrentPosition();
});
}
更多信息可以在here和here找到。