使用GraphQLClient与GetIt,Inejctable时出现问题,但它使用旧实例?扑朔迷离

问题描述

我觉得我迷路了。因此,请您帮忙! 在我的项目中,我正在使用GraphQL Flutter包。 我将GetIt用于服务定位器,并将可注入代码生成器用于getIt。这是我的代码。 我的代码看起来像这样。

GraphQLClient的client.dart

class Client {
  GraphQLClient client() {
    final httpLink = HttpLink(uri: httpEndpoint);
    final wsLink = WebSocketLink(
      url: wsEndpoint,config: SocketClientConfig(
        autoReconnect: true,inactivityTimeout: Duration(seconds: 30),),);

    Box = getIt<Box>();
    token = Box.get('userToken');
    final authLink = AuthLink(getToken: () async => 'Bearer $token');
    final Link link = authLink.concat(httpLink).concat(wsLink);
    GraphQLClient _client = GraphQLClient(cache: InMemoryCache(),link: link);
    return _client;
  }
}

然后我使用可注入注释将其注册到register_module.dart中。

@module
abstract class RegisterModule {
  @singleton
  GraphQLClient get gqlClient => Client().client();
}

其他功能运行良好,例如使用GraphQLClient更改用户信息等。 但是注销功能使用的是旧的吗?或其他? GraphQLClient。我这样想的原因是,在服务器日志中,我看到了旧的“ Bearer userToken”。

调用logout函数时,在GraphQLClient实例中使​​用旧(最后)userToken。

注销功能如下

Future<void> logout() async {
    Session session = getIt<Session>();

    final String token = session.token;
    final result = await _client.mutate(Mutationoptions(
        documentNode: gql(signOut),variables: {"token": token}));

    if (result == null) return null;

    if (result.hasException) {
      print("Printing error from logout: ${result.exception.toString()}");
      throw ServerException();
    }

    // session is deleted from server
    // then delete session from client.
    // unregister session instance.
    getIt.unregister<Session>();

    // Delete session token
    await _Box.delete("userToken");
    String userToken = await _Box.get("userToken");
    
    updateClient();
    _controller.add(AuthenticationStatus.unauthenticated);
    return null;
  }

and updateClient()会检查是否已注册(旧)客户端实例,如果是,请取消注册客户端实例,然后重新注册新实例。

void updateClient() {
  // Create new GraphQLClient insntace
  final client = Client().client();

  if (getIt.isRegistered<GraphQLClient>()) {
    getIt.unregister<GraphQLClient>();
    getIt.registerSingleton<GraphQLClient>(client);
  } else {
    getIt.registerSingleton<GraphQLClient>(client);
  }
}

然后我使用Hive软件包将userToken保存在框中。

知道我在哪里做错了吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)