异步对象未向 get_it 注册

tvl*_*tvl 1 asynchronous dependency-injection inversion-of-control dart flutter

我正在将 get_it 用于 IoC。但是,当我尝试使用异步调用注册 bean 时,我的应用程序抛出异常。抛出异常的函数:

import 'package:elpee/service/localstorage_service.dart';
import 'package:get_it/get_it.dart';


GetIt locator = GetIt();
Future setupLocator() async {
  LocalStorageService.getInstance().then((storageService) {
    locator.registerSingleton(storageService);
  });
}
Run Code Online (Sandbox Code Playgroud)

错误: Exception: Object of type LocalStorageService is not registered inside GetIt

如果有人可以帮助我,我将不胜感激:-)

Kam*_*oda 6

您正试图以错误的方式使用 get_it。检查文档

首先 - get_it 是 Singleton,因此不要使用构造函数,但是

GetIt locator = GetIt.instance;
Run Code Online (Sandbox Code Playgroud)

第二 - 将 LocalStorageService 实现为一个普通类,并让 get_it 将其作为单例提供:

void main()
...
   void setupLocator() {
     locator.registerLazySingleton(LocalStorageService());
   }
}
Run Code Online (Sandbox Code Playgroud)

要使用 IoC 的全部功能,请为您的存储服务定义接口/抽象类定义并提供接口的实现。

void setupLocator() {
  locator.registerLazySingleton<IStorageService>(LocalStorageService());
}
Run Code Online (Sandbox Code Playgroud)