sqlite Flutter get_it工厂尚未准备就绪[Flutter get_it库与Floor数据库初始化]

mcdcgff0  于 2023-01-31  发布在  SQLite
关注(0)|答案(1)|浏览(157)

我正在尝试使用floor库和get_it库来简化调用
这个库简单实现是:

final sl = GetIt.instance;

Future<void> init() async {
  /// database
  sl.registerLazySingletonAsync<AppDatabase>(
      () => $FloorAppDatabase.databaseBuilder('app_database.db').build());

  /// http client
  sl.registerLazySingleton<ApiService>(
      () => NetworkModule().getHttpProvider().getService());

  /// call dao
  sl.registerLazySingletonAsync<UserDao>(
      () async => (await sl.getAsync<AppDatabase>()).userDao);

在main()函数中,我调用:
等待sl.初始化();
但我得到错误:

You tried to access an instance of UserDao that is not ready yet
'package:get_it/get_it_impl.dart':
package:get_it/get_it_impl.dart:1
Failed assertion: line 404 pos 9: 'instanceFactory.isReady'

我的代码有什么问题??谢谢
我已将答案引用到此https://stackoverflow.com/questions/56497896/make-a-simple-single-instanse-class-as-database-helper

r7xajy2e

r7xajy2e1#

使用dependsOn参考www.example.com并链接其每个模块。https://pub.dev/packages/get_it#automatic-using-dependson and chaining that its each module.
例如:

getIt.registerSingletonAsync<AppDatabase>(() async => $FloorAppDatabase
      .databaseBuilder('app_database.db')
      .addCallback(callback)
      .build());

getIt.registerSingletonWithDependencies<UserDao>(
      () => getIt<AppDatabase>().userDao,
      dependsOn: [AppDatabase]);

相关问题