You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决background_locator回调调用shared_preferences报MissingPluginException问题

Flutter background_locator 回调读取 shared_preferences 报错解决方案

报错根因

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 13:39:00