簡體   English   中英

無法使用 Get_it 在顫振中初始化 GraphQl 客戶端

[英]Can't initialized GraphQl Client in flutter using Get_it

我想在我的 Flutter 應用程序中實現 GraphQL 客戶端。 對於依賴注入,我使用 GetIt 庫。 但是當我運行應用程序時,它說

'無效參數(HomeGraphQLService 類型的對象未在 GetIt 中注冊。您是否忘記傳遞實例名稱?(您是否不小心執行了 GetIt sl=GetIt.instance(); 而不是 GetIt sl=GetIt.instance;)):HomeGraphQLService '

.

這意味着 GraphQL 客戶端沒有以某種方式實例化,盡管我在我的服務定位器中注冊了它

Session.dart

abstract class Session {
  String getAccessToken();
}

SessionImpl.dart

class SessionImpl extends Session {
  SharedPreferences sharedPref;

  SessionImpl(SharedPreferences sharedPref) {
    this.sharedPref = sharedPref;
  }

  @override
  String getAccessToken() {
    return sharedPref.getString('access_token') ?? "";
  }

}

GraphQLClientGenerator.dart

class GraphQLClientGenerator {
  Session session;

  GraphQLClientGenerator(Session session) {
    this.session = session;
  }

  GraphQLClient getClient() {
    final HttpLink httpLink = HttpLink('https://xxx/graphql');
    final AuthLink authLink = AuthLink(getToken: () async => 'Bearer ${_getAccessToken()}');
    final Link link = authLink.concat(httpLink);

    return GraphQLClient(link: link, cache: GraphQLCache(store: InMemoryStore()));
  }

  String _getAccessToken() {
    return session.getAccessToken();
  }
}

HomeRepository.dart

abstract class HomeRepository {
  Future<List<Course>> getAllCourseOf(String className, String groupName);
}

HomeRepositoryImpl.dart

class HomeRepositoryImpl extends HomeRepository {

  HomeGraphQLService homeGraphQLService;
  HomeMapper homeMapper;

  HomeRepositoryImpl(HomeGraphQLService homeGraphQLService, HomeMapper homeMapper) {
    this.homeGraphQLService = homeGraphQLService;
    this.homeMapper = homeMapper;
  }

  @override
  Future<List<Course>> getAllCourseOf(String className, String groupName) async {
    final response = await homeGraphQLService.getAllCourseOf(className, groupName);
    return homeMapper.toCourses(response).where((course) => course.isAvailable);
  }

}

HomeGraphQLService.dart

class HomeGraphQLService {
  GraphQLClient graphQLClient;

  HomeGraphQLService(GraphQLClient graphQLClient) {
    this.graphQLClient = graphQLClient;
  }

  Future<SubjectResponse> getAllCourseOf(String className, String groupName) async {
    try {
      final response = await graphQLClient.query(getAllCourseQuery(className, groupName));
      return SubjectResponse.fromJson((response.data));
    }  catch (e) {
      return Future.error(e);
    }
  }
}

GraphQuery.dart

QueryOptions getAllCourseQuery(String className, String groupName) {
  String query = """
    query GetSubject($className: String, $groupName: String) {
      subjects(class: $className, group: $groupName) {
        code
        display
        insights {
          coming_soon
          purchased
        }
      }
    }
    """;

  return QueryOptions(
    document: gql(query),
    variables: <String, dynamic>{
      'className': className,
      'groupName': groupName,
    },
  );
}

ServiceLocator.dart

final serviceLocator = GetIt.instance;

Future<void> initDependencies() async {
  await _initSharedPref();
  _initSession();
  _initGraphQLClient();
  _initGraphQLService();
  _initMapper();
  _initRepository();
}

Future<void> _initSharedPref() async {
  SharedPreferences sharedPref = await SharedPreferences.getInstance();
  serviceLocator.registerSingleton<SharedPreferences>(sharedPref);
}

void _initSession() {
  serviceLocator.registerLazySingleton<Session>(()=>SessionImpl(serviceLocator()));
}

void _initGraphQLClient() {
  serviceLocator.registerLazySingleton<GraphQLClient>(() => GraphQLClientGenerator(serviceLocator()).getClient());
}

void _initGraphQLService() {
  serviceLocator.registerLazySingleton<HomeGraphQLService>(() => HomeGraphQLService(serviceLocator()));
}

void _initMapper() {
  serviceLocator.registerLazySingleton<HomeMapper>(() => HomeMapper());
}

void _initRepository() {
  serviceLocator.registerLazySingleton<HomeRepository>(() => HomeRepositoryImpl(serviceLocator(), serviceLocator()));
}

main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SystemChrome.setPreferredOrientations(
    [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
  );
  
  await initDependencies();

  runApp(MyApp());
}

我不能說它到底發生在哪里,因為它在您訪問GraphQLService代碼中的其他地方,但問題肯定是由於延遲加載造成的。 在訪問對象之前, locator尚未創建和加載該對象。 嘗試更新ServiceLocator.dart以在注冊期間實例化類,如下所示:

void _initSession() {
  serviceLocator.registerSingleton<Session>.(SessionImpl(serviceLocator()));
}

void _initGraphQLClient() {
  serviceLocator.registerSingleton<GraphQLClient>(
    GraphQLClientGenerator(serviceLocator()).getClient());
}

void _initGraphQLService() {
  serviceLocator.registerSingleton<HomeGraphQLService>(
    HomeGraphQLService(serviceLocator()));
}

void _initMapper() {
  serviceLocator.registerSingleton<HomeMapper>(HomeMapper());
}

void _initRepository() {
  serviceLocator.registerSingleton<HomeRepository>(
    HomeRepositoryImpl(serviceLocator(), serviceLocator()));
}

給你:我不能說它到底發生在哪里,因為它在你訪問 GraphQLService 的代碼中的其他地方,但問題肯定是由於延遲加載造成的。 在訪問對象之前,定位器尚未創建和加載該對象。 嘗試更新 ServiceLocator.dart 以在注冊期間實例化類,如下所示:

  serviceLocator.registerSingleton<Session>.(SessionImpl(serviceLocator()));
}

void _initGraphQLClient() {
  serviceLocator.registerSingleton<GraphQLClient>(
    GraphQLClientGenerator(serviceLocator()).getClient());
}

void _initGraphQLService() {
  serviceLocator.registerSingleton<HomeGraphQLService>(
    HomeGraphQLService(serviceLocator()));
}

void _initMapper() {
  serviceLocator.registerSingleton<HomeMapper>(HomeMapper());
}

void _initRepository() {
  serviceLocator.registerSingleton<HomeRepository>(
    HomeRepositoryImpl(serviceLocator(), serviceLocator()));
}```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM