D/FlutterGeolocator( 2882): Disposing Geolocator services
E/FlutterGeolocator( 2882): Geolocator position updates stopped
D/FlutterGeolocator( 2882): Stopping location service.
I/WM-WorkerWrapper( 2882): Worker result SUCCESS for Work [ id=dc416b8a-e86b-4976-b078-9e8698ac1399, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
E/flutter ( 2882): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method getCurrentPosition on channel flutter.baseflow.com/geolocator)
我试图在后台获取当前位置。我使用了这些包:
workmanager: ^0.4.0
geolocator: ^8.0.0
我遵循这个教程
我的代码很简单
1。回调函数或静态主函数
//callback function
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
await LocationService.getCurrentLocation();
print("Native called background task-1: $task");
return Future.value(true);
});
}
2。init函数(我在initstate上调用了这些函数)
Workmanager().initialize(
callbackDispatcher,
isInDebugMode: true,
);
Workmanager().registerPeriodicTask(
"22",
fetchBackground,
initialDelay: Duration(seconds: 30),
frequency: Duration(minutes: 30),
);
3。最后一个函数是getcurrentlocation
class LocationService {
static getCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.best);
print(position );
}
}
当executeTask
运行时尝试注册Android特定实现
//callback function
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 LocationService.getCurrentLocation();
print("Native called background task-1: $task");
return Future.value(true);
});
}
或者,如果您正在运行Flutter 2.11+,您可以使用新的DartPluginRegistrant.ensureInitialized()
方法来确保所有包都被正确注册:
//callback function
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
DartPluginRegistrant.ensureInitialized();
await LocationService.getCurrentLocation();
print("Native called background task-1: $task");
return Future.value(true);
});
}
问题是该任务在单独的隔离中运行,该隔离在没有Flutter引擎的情况下执行。因此,平台特定的实现(在本例中为geolocator_android
)没有注册到平台接口(geolocator_platform_interface
),从而导致MissingPluginException
。
更多信息可以在这里和这里找到。