如何解决background_locator回调调用shared_preferences报MissingPluginException问题
报错根因
background_locator 的定位回调运行在*独立隔离区(Isolate)*中,和应用主Isolate内存互不共享,默认新Isolate不会自动完成Flutter原生插件的注册,因此调用依赖平台通道实现的shared_preferences时,就会抛出MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)异常。
解决步骤
- 步骤1:在回调方法开头补充Isolate的插件绑定逻辑
在你的定位回调方法第一行添加WidgetsFlutterBinding.ensureInitialized(),完成当前Isolate的插件注册,修改后代码如下:
static void callback(LocationDto locationDto) async { // 新增此行,初始化当前Isolate的插件绑定 WidgetsFlutterBinding.ensureInitialized(); await SharedPrefs().init(); var id = SharedPrefs().deviceLocationId; print('deviceLocationId $id'); await saveLocation(locationDto.latitude, locationDto.longitude); final SendPort send = IsolateNameServer.lookupPortByName('LocatorIsolate'); send.send(locationDto); }
- 步骤2:升级依赖版本
确保shared_preferences依赖升级到2.0.0及以上版本,旧版本存在Isolate兼容问题,升级后需要清理缓存重新编译应用。 - 步骤3:Android端额外兼容(仅适用于修改后仍报错的场景)
打开Android项目目录下的android/app/src/main/kotlin/[你的应用包名]/MainActivity.kt,在onCreate方法中主动触发shared_preferences插件注册,或者在启动定位前提前把设备ID通过IsolateNameServer传递给定位隔离区,避免在回调中读取本地存储。
内容的提问来源于stack exchange,提问作者Mohammad ozair
相关产品推荐
相关产品推荐

