Created
January 27, 2021 10:53
-
-
Save kwaiks/850161faf557ee4d7ed9a2b6fe972ea5 to your computer and use it in GitHub Desktop.
Flutter Dio Interceptor for refresh token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DioHelper { | |
final Dio dio; | |
DioHelper({@required this.dio}); | |
final CustomSharedPreferences _customSharedPreferences = | |
new CustomSharedPreferences(); | |
static String _baseUrl = BASE_URL; | |
String token = ""; | |
void initializeToken(String savedToken) { | |
token = savedToken; | |
_initApiClient(); | |
} | |
Future<void> initApiClient() { | |
dio.interceptors | |
.add(InterceptorsWrapper(onRequest: (RequestOptions options) { | |
options.headers["Authorization"] = "Bearer " + token; | |
return options; | |
}, onResponse: (Response response) { | |
return response; | |
}, onError: (DioError error) async { | |
RequestOptions origin = error.response.request; | |
if (error.response.statusCode == 401) { | |
try { | |
Response<dynamic> data = await dio.get("your_refresh_url"); | |
token = data.data['newToken']; | |
_customSharedPreferences.setToken(data.data['newToken']); | |
origin.headers["Authorization"] = "Bearer " + data.data['newToken']; | |
return dio.request(origin.path, options: origin); | |
} catch (err) { | |
return err; | |
} | |
} | |
return error; | |
})); | |
dio.options.baseUrl = _baseUrl; | |
} | |
Future<dynamic> get(String url) async { | |
try { | |
final response = await dio.get(url); | |
var apiResponse = ApiResponse.fromJson(response.data); | |
if (apiResponse.status != 200) { | |
throw Exception(apiResponse.message); | |
} | |
return apiResponse.data; | |
} on DioError catch (e) { | |
// debugging purpose | |
print('[Dio Helper - GET] Connection Exception => ' + e.message); | |
throw e; | |
} | |
} | |
Future<dynamic> post(String url, | |
{Map headers, @required data, encoding}) async { | |
try { | |
final response = | |
await dio.post(url, data: data, options: Options(headers: headers)); | |
ApiResponse apiResponse = ApiResponse.fromJson(response.data); | |
if (apiResponse.status != 200) { | |
throw Exception(apiResponse.message); | |
} | |
return apiResponse.data; | |
} on DioError catch (e) { | |
// debugging purpose | |
print('[Dio Helper - GET] Connection Exception => ' + e.message); | |
throw e; | |
} | |
} | |
} |
there is an example here to navigate to login page. https://medium.com/flutter-community/dio-interceptors-in-flutter-17be4214f363
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can we navigate the user to the login page after we get status code 401?