【问题标题】:How to use SharedPreferences and Injectable in Flutter?如何在 Flutter 中使用 SharedPreferences 和 Injectable?
【发布时间】:2020-08-25 16:20:03
【问题描述】:

我在 Flutter 中使用库 Injectable 进行依赖注入,但在无法使用 SharedPreferences 时出现错误。

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

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

我试着把 WidgetsFlutterBinding.ensureInitialized()

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

【问题讨论】:

    标签: flutter dependency-injection sharedpreferences


    【解决方案1】:

    您可以在SharedPreference 中通过注释@preResolve 预先等待未来

    @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());
    }
    

    【讨论】:

      【解决方案2】:

      以下是我得到它的工作方式,不保证它是最好的方法。

      等待main方法中的configureInjection方法。

      void main() async {
        WidgetsFlutterBinding.ensureInitialized();
        await configureInjection(Env.prod);
        runApp(App());
      }
      

      然后将您的应用程序包装在使用 getIt.allReady() 的 FutureBuilder 中。

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

      有用的链接:

      【讨论】:

        猜你喜欢
        • 2021-01-16
        • 2019-09-30
        • 2018-09-11
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2022-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多