如何在Flutter中使用SharedPreferences和Injectable?

4
我正在使用Flutter中的Injectable库进行依赖注入,但是我遇到了一个错误,无法使用SharedPreferences。
错误信息: 异常已出现。 FlutterError (在绑定初始化之前,访问了ServicesBinding.defaultBinaryMessenger。 如果你正在运行应用程序并需要在调用runApp()之前访问二进制信使(例如,在插件初始化期间),那么你需要先显式调用WidgetsFlutterBinding.ensureInitialized()。 如果你正在运行测试,则可以在测试的main()方法中作为第一行调用TestWidgetsFlutterBinding.ensureInitialized()来初始化绑定。)
我尝试过创建一个类并添加@lazySingleton。
  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

我尝试使用WidgetsFlutterBinding.ensureInitialized()

void main() { 
  WidgetsFlutterBinding.ensureInitialized();
  configureInjection(Environment.prod);
  runApp(MyApp());
}
2个回答

7

通过使用@preResolve注解,您可以在SharedPreference中预先等待未来。

@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 之间的差异。

请记得像这样使用它:final prefs = getIt<SharedPreferences>(); await prefs.setString('city', city); .... 不要使用getIt<InjectionModule>()。 - Martin Berger

0
以下是我让它工作的方法,不保证这是最好的方法。
在主方法中等待configureInjection方法。
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await configureInjection(Env.prod);
  runApp(App());
}

并在FutureBuilder中包装您的应用程序,利用getIt.allReady()

Widget build(context) {
  return FutureBuilder(
    future: getIt.allReady(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        // ... your app widgets
      } else {
        // ... some progress indicator widget
      }
    }
  );
}

有用的链接:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接