我正在为IoC使用get_it。但是,当我尝试使用异步调用注册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);
  });
}

错误:Exception: Object of type LocalStorageService is not registered inside GetIt
如果有人可以帮助我,我将不胜感激:-)

最佳答案

您正在尝试以错误的方式使用get_it。检查到documentation

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

GetIt locator = GetIt.instance;

第二个-将LocalStorageService实现为普通类,并让get_it将其作为Singleton提供:
void main()
...
   void setupLocator() {
     locator.registerLazySingleton(LocalStorageService());
   }
}

要使用IoC的全部功能,请为您的storageservice定义接口(interface)/抽象类定义,并提供该接口(interface)的实现。
void setupLocator() {
  locator.registerLazySingleton<IStorageService>(LocalStorageService());
}

关于asynchronous - 异步对象未向get_it注册,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59093014/

10-10 17:07