How to change the value of a variable in GetIt?

94 Views Asked by At

While researching GetIt, I came across the following problem.

I have a class for queries

class Query {
  // late String query;
  // String? query;
  String query = 'Obama';
  final String elonMusk = 'Elon Musk';
}

My class for API:


class NewsApi {
  final Dio dio;
  final String apiKey;
  final String query;
  NewsApi({required this.dio, required this.apiKey, required this.query});
  Future<List<NewsEntity>> getRecentNews() async {
    final res = await dio
        // .get('/v2/everything?q=singapore&sortBy=publishedAt&apiKey=$apiKey'); // Original
        .get('/v2/everything?q=$query&sortBy=publishedAt&apiKey=$apiKey');
    return List<Map<String, dynamic>>.from(res.data['articles'])
        .map((e) => NewsEntity.fromJson(e))
        .toList();
  }
}

My service locator:

...
serviceLocator.registerLazySingleton<NewsApi>(() => NewsApi(
      dio: serviceLocator<Dio>(), apiKey: serviceLocator<Constant>().apiKey, query: serviceLocator<Query>().query));

And a bloc file where I try to change the value of serviceLocator().query

class MainNewsBloc extends Bloc<MainNewsEvent, MainNewsState> {
  MainNewsBloc() : super(MainNewsInitialState()) {
    on<MainNewsGetRecentNewsEvent>(mainNewsGetRecentNewsEvent);
  }

  FutureOr<void> mainNewsGetRecentNewsEvent(
      MainNewsGetRecentNewsEvent event, Emitter<MainNewsState> emit) async {
    try {
      emit(MainNewsLoadingState());

      // Using serviceLocator
      serviceLocator<Query>().query = event.query;
      print('serviceLocator<Query>().query is ${serviceLocator<Query>().query}');
      print('event.query is ${event.query}');


      // Using Query instance creation
      // Query myQuery = Query();
      // myQuery.query = event.query;
      // print('serviceLocator<Query>().query is ${serviceLocator<Query>().query}');
      // print('myQuery.query is ${myQuery.query}');
      // print('event.query is ${event.query}');


      List<NewsEntity> news =
          await serviceLocator<GetRecentNewsUseCase>().call();
      emit(MainNewsGetRecentNewsSuccessState(news));
    } catch (e) {
      emit(MainNewsErrorState("Something Went Wrong"));
    }
  }
}

The console shows the following:

I/flutter (19090): serviceLocator().query is Obama I/flutter (19090): event.query is Elon Musk

That is, I tried to assign a new value to the query variable, taking it from event.query, but it did not happen. Why? And how to fix it?

Right now it's just an experiment. But in the future I want to pass arbitrary values that users will enter in the form.

And yes, if I declare the query variable differently (for example, late String query or String? query), then it gets even worse.

That is, the problem is that the code in my bloc file does not work.

0

There are 0 best solutions below