gpt4 book ai didi

flutter - 如何在 Flutter 中使用 SharedPreferences 和 Injectable?

转载 作者:行者123 更新时间:2023-12-05 02:07:32 27 4
gpt4 key购买 nike

我在 flutter 中使用库 Injectable 进行依赖注入(inject),但我收到无法使用 SharedPreferences 的错误。

错误:发生异常。FlutterError(在初始化绑定(bind)之前访问了 ServicesBinding.defaultBinaryMessenger。如果您正在运行一个应用程序并且需要在调用 runApp() 之前访问二进制信使(例如,在插件初始化期间),那么您需要显式调用 WidgetsFlutterBinding.ensureInitialized () 首先。如果您正在运行测试,则可以在测试的 main() 方法的第一行调用 TestWidgetsFlutterBinding.ensureInitialized() 来初始化绑定(bind)。)我已经尝试创建一个类并放置@lazySingleton

  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

我试着把 WidgetsFlutterBinding.ensureInitialized() 放在

void main() { 
WidgetsFlutterBinding.ensureInitialized();
configureInjection(Environment.prod);
runApp(MyApp());
}

最佳答案

您可以通过使用 @preResolve 注释在 SharedPreference 中预等待 future

@module
abstract class InjectionModule {

//injecting third party libraries
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}

configureInjection 类上

final GetIt getIt = GetIt.instance;

@injectableInit
Future<void> configureInjection(String env) async {
await $initGetIt(getIt, environment: env);
}

还有主类

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureInjection(Environment.prod);
runApp(MyApp());
}

实际使用:

final prefs = getIt<SharedPreferences>();
await prefs.setString('city', city);

不是:

final module = getIt<InjectionModule>();
module.prefs.setString('test', test);

注意 SharedPreferencesInjectionModule 之间的区别。

关于flutter - 如何在 Flutter 中使用 SharedPreferences 和 Injectable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61707450/

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