flutterdependency-injectiondioinjectable

How to change the dependency at runtime using the flutter injectable library?


I am developing a flutter application that uses injectable and get_it libraries.

And I have a Dio reference that contains Auth token which is getting from the LocaleStorage service. When I change it at runtime it is not getting updated. Because of it I am getting the unauthorized user error from the API service.

Here is the my module ⤵️

@module
abstract class NetworkingModule {

  Dio getDio(UserModelLocalStorageService localStorageService) {
    final Dio dio = Dio()
      ..interceptors.addAll([
        if (!kReleaseMode) PrettyDioLogger(requestBody: true, requestHeader: true),
      ]);
    dio.options.headers["device-id"] = "1uazj1234";
    dio.options.headers["Authorization"] = localStorageService.getAccessToken();
    return dio;
  }

  @lazySingleton
  AuthApiService getCharacterListApiService(Dio dio, AppConfig appConfig) =>
      AuthApiService(dio, baseUrl: appConfig.baseUrl);
  
}

Thanks in advance,


Solution

  • You can solve this problem as follows ⤵️

    final Dio dio = Dio();
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, interceptor) async {
          final token = localStorageService.getAccessToken().toBearer();
          options.headers["Authorization"] = token;
          interceptor.next(options);
        },
        onError: (e, interceptor) async {
          // do something here if call fails, for example token refresh if it is expired
        },
      ),
    );
    

    Kudos to @martirius for the solution 🙏