Search code examples
flutterretrofit

How to add Bearer token Authorization in Retrofit Flutter


How to add Bearer token Authorization in Retrofit Flutter.

Here is Retrofit Service

@RestApi(baseUrl: "https://***.****.xyz/api/")
abstract class ApiService{

  factory ApiService(Dio dio) => _ApiService(dio);

  @POST("auth/login")
  Future<AuthModel> login(@Body() Map<String,dynamic> map);

  @POST("auth/singup")
  Future<AuthModel> singup(@Body() Map<String,dynamic> map);

  @GET('{id}')
  Future<UserModel> getUser( @Path() String id);

}

And Then Create Dio and add into GetIt and insert into ApiService.

var getIt = GetIt.I;
void locator(){

  Dio dio = Dio();
  

  getIt.registerLazySingleton(() => dio);

   ApiService apiService = ApiService(getIt.call());
  getIt.registerLazySingleton(() => apiService);

  Repository repository = Repository(getIt.call());
  getIt.registerLazySingleton(() => repository);

  LoginCubit loginCubit = LoginCubit(getIt.call());
  getIt.registerLazySingleton(() => loginCubit);
 
  GetProfileCubit getProfileCubit = GetProfileCubit(getIt.call());
  getIt.registerLazySingleton(() => getProfileCubit);

}

and Create Repository

class Repository{
  final ApiService _apiService;
  Repository(this._apiService);

  Future<AuthModel> logIn(Map<String,dynamic> map) => _apiService.login(map);
  Future<AuthModel> singUp(Map<String,dynamic> map) => _apiService.singup(map);
  Future<UserModel> getUser(String id) => _apiService.getUser(id);

} 

Please answer my question sir. Sorry for my english.


Solution

  • This is not the optimal way but this should work fine.

    Change your ApiService class as follows:

    @RestApi(baseUrl: "https://***.****.xyz/api/")
    abstract class ApiService{
    
       .... same code ....
    
      @GET('{id}')
      Future<UserModel> getUser( 
         @Header('Authorization') String token,
         @Path() String id
           );
    
     .... same code ....
    }
    

    Also change your Repository class:

    class Repository{
      .... same code ...
      //// Pass token as a parameter
      ///// Add Bearer before your token
     
      Future<UserModel> getUser(String token, String id) => 
          _apiService.getUser('Bearer $token',id);
    
    } 
    

    Happy Coding TT