How to update a get it instance in flutter?

Viewed 159

I am using the getIt package to create instances in my application.

instance.registerLazySingleton<DioFactory>(() => DioFactory(instance()));

  // app  service client
  final dio = await instance<DioFactory>().getDio();
  instance.registerLazySingleton<AppServiceClient>(() => AppServiceClient(dio));

Above code is for initialising the instances. The getDio() function:

Future<Dio> getDio() async {
    Dio dio = Dio();
    int _timeOut = 60 * 1000; // 1 min
    String language = await _appPreferences.getAppLanguage();
    Map<String, String> headers = {
      CONTENT_TYPE: APPLICATION_JSON,
      ACCEPT: APPLICATION_JSON,
      AUTHORIZATION: Constants.token,
      DEFAULT_LANGUAGE: language
    };

    dio.options = BaseOptions(
        baseUrl: Constants.baseUrl,
        connectTimeout: _timeOut,
        receiveTimeout: _timeOut,
        headers: headers);

    if (kReleaseMode) {
    } else {
      dio.interceptors.add(PrettyDioLogger(
          requestHeader: true, requestBody: true, responseHeader: true));
    }

    return dio;
  }

When I build my application for the first time the Constants.token has a blank value. But in the middle of the application I wish to add a value into it. I am able to change that value but when I see the logs from dio logger it still displays the empty string in the "Authorisation" field.

How do I update my instance so that I can change my token value for my API requests?

2 Answers

you have to register your dio with registerFactory to getit. In your case you are registering as singleton, that's why it is giving you same instance

First you should create an interceptor that call TokenInterceptor with override onRequest method. Inside onRequest method you can modify your headers like below:

https://i.stack.imgur.com/T6PFR.png

And final step you only add to your dio interceptor like that:

dio.interceptors.add(TokenInterceptor());
Related