我想从Hive
中检索sessionToken
和authToken
,然后将其放入GraphQLClient
- 主省道**
GetIt sl = GetIt.instance;
void main() async {
// Register Service locator
await initAuthServiceLocator(sl);
....
await sl.allReady();
runApp(...);
}
- 初始化身份验证服务定位器**
Future<void> initAuthServiceLocator(
GetIt sl, {
isUnitTest = false,
}) async {
if (!isUnitTest) {
await Hive.initFlutter();
....
sl.registerLazySingleton<Future<GraphQLClient>>(() => GraphQLClientGenerator().getClient());
....
}
- GraphQL客户端生成器**
class GraphQLClientGenerator {
GraphQLClientGenerator();
Future<GraphQLClient> getClient() async {
final authUserBox = await Hive.openLazyBox('authUserBox');
var box = await authUserBox.getAt(0);
debugPrint(box);
final HttpLink httpLink = HttpLink(
'https://xxx/graphqlmf?session_token="Get from box");
final AuthLink authLink =
AuthLink(getToken: () async => "Get from box");
final Link link = authLink.concat(httpLink);
return GraphQLClient(link: link, cache: GraphQLCache());
}
}
我是这样注册的
sl.registerLazySingleton<Future<GraphQLClient>>(() => GraphQLClientGenerator().getClient());
- 错误**
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building KeyedSubtree-[GlobalKey#1bbd2]:
Object/factory with type GraphQLClient 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':
get_it_impl.dart:1
Failed assertion: line 372 pos 7: 'instanceFactory != null'
注册GraphQLClient
时好像不能添加Future
。如果我想在GraphQLClient
中调用Hive
,因为它需要async-await
,正确的方法是什么?
- 编辑**
等我换成
sl.lazySingletonAsync<GraphQLClient>(GraphQLClientGenerator().getClient);
- 新错误**
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building KeyedSubtree-[GlobalKey#6665b]:
You tried to access an instance of GraphQLClient that is not ready yet
'package:get_it/get_it_impl.dart':
get_it_impl.dart:1
Failed assertion: line 404 pos 9: 'instanceFactory.isReady'
我已经在main.dart
中添加了await sl.allReady();
,但仍然得到这个问题。
2条答案
按热度按时间m4pnthwp1#
使用
injectable
库中的@preResolve
注解解决此问题。这在使用
build_runner
自动生成代码时有效。使用
lazySingletonAsync
by解决此问题。nle07wnf2#
为了修复这个新错误,我使用了
isReady
。