gpt4 book ai didi

具有共享首选项的 Flutter 依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-05 04:55:22 26 4
gpt4 key购买 nike

晚上好我正在尝试将依赖注入(inject)与共享首选项插件一起使用,但是一旦我生成代码,我就会收到一个不相关的 Bloc 的错误。我用

  • 获取它:^0.5.3,
  • injectable_generator:1.0.6
  • flutter_bloc: ^6.1.1.

我的目标是将 SharedPreferences 注入(inject)到一个用于处理本地操作的类中,它看起来像这样:

class LocalSharedPreferences {
final SharedPreferences _preferences;

LocalSharedPreferences(this._preferences);
...
}

为了正确注入(inject) SharedPreferences,我遵循了它的官方文档 (https://pub.dev/packages/injectable#registering-asynchronous-injectables),因此我注入(inject)第 3 方模块的代码如下所示:

@module
abstract class RegisterModule {
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}

我关注了this关于 StackOverflow 的问题,但它没有用。我的错误如下:

The following assertion was thrown building SignInForm(dependencies: [MediaQuery]):
Object/factory with type SignInFormBloc is not registered inside GetIt.
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
Did you forget to register it?)
'package:get_it/get_it_impl.dart':
Failed assertion: line 298 pos 9: 'instanceFactory != null'

自动生成的注入(inject)代码如下所示:

Future<GetIt> $initGetIt(
GetIt get, {
String environment,
EnvironmentFilter environmentFilter,
}) async {
final gh = GetItHelper(get, environment, environmentFilter);
final registerModule = _$RegisterModule();
gh.factory<DatosBauServerApiHelper>(() => DatosBauServerApiHelper());
gh.factory<DatosBauServerAuth>(
() => DatosBauServerAuth(get<DatosBauServerApiHelper>()));
gh.lazySingleton<IAuthFacade>(
() => DatosBauServerAuthFacade(get<DatosBauServerAuth>()));
final sharedPreferences = await registerModule.prefs;
gh.factory<SharedPreferences>(() => sharedPreferences);
gh.factory<SignInFormBloc>(() => SignInFormBloc(get<IAuthFacade>()));
return get;
}

class _$RegisterModule extends RegisterModule {}

最佳答案

包裹Get it

LocalSharedPreferences 类

abstract class LocalSharedPreferences {
// ...
}

LocalSharedPreferencesImpl 类

class LocalSharedPreferencesImpl extends LocalSharedPreferences {
// ...
// Use your globalSharedPrefs variable here
}

另一个飞镖文件

GetIt locator = GetIt.instance;

setupServicesLocator() {
locator.registerLazySingleton<LocalSharedPreferences>(() => LocalSharedPreferencesImpl());
}

你的 main.dart 文件

SharedPreferences globalSharedPrefs;

void main() async {
/* ENSURE ASYNC WILL NOT GENERATE RUNTIME ERROR */
WidgetsFlutterBinding.ensureInitialized();

/* GLOBAL SERVICES */
setupServicesLocator();

/* Initialize your globalSharedPreferences variable here */
globalSharedPrefs = await SharedPreferences.getInstance();
}

关于具有共享首选项的 Flutter 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65416825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com