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

Flutter中使用GetIt获取RepositoryImpl触发未处理异常求助

问题解决:GetIt未找到实例的异常处理

问题根源

你在setupLocator中注册的是抽象类型Repository对应的实现类RepositoryImpl,但在后台回调backgroundCallback里,尝试直接获取具体类RepositoryImpl的实例——GetIt只认你注册时声明的类型,所以找不到对应的工厂,抛出异常。

修复方案

方案一(推荐):通过抽象类型获取实例

修改backgroundCallback中的代码,用注册时的抽象类型Repository来获取实例:

Future<void> backgroundCallback(Uri? uri) async {
  Repository repository = locator<Repository>();
  ...
}

这个方案符合依赖倒置原则,降低代码耦合,也是依赖注入的标准用法。

方案二:额外注册具体实现类

如果业务场景确实需要直接获取RepositoryImpl,可以在setupLocator中补充注册该具体类:

void setupLocator() {
  locator.registerLazySingleton(() => PreferenceProvider());
  locator.registerLazySingleton(() => CurrencyApi.create());
  locator.registerLazySingleton(() => BackupCurrencyApi.create());
  // 原有的抽象类型注册
  locator.registerLazySingleton<Repository>(() => RepositoryImpl(locator<PreferenceProvider>(), locator<CurrencyApi>(),locator<BackupCurrencyApi>()));
  // 新增具体类注册
  locator.registerLazySingleton(() => RepositoryImpl(locator<PreferenceProvider>(), locator<CurrencyApi>(),locator<BackupCurrencyApi>()));
  ...
}

额外说明

你在main函数中先执行setupLocator再注册后台回调的顺序是正确的,确保了GetIt在回调执行前已经完成初始化,无需调整顺序。

内容的提问来源于stack exchange,提问作者Haider Malik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:10:51