intercept.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import 'package:dio/dio.dart';
  2. import 'package:flutter/material.dart';
  3. class DioPage extends StatefulWidget {
  4. @override
  5. State<StatefulWidget> createState() {
  6. return _DioPageState();
  7. }
  8. }
  9. class _DioPageState extends State<DioPage> {
  10. Dio dio = Dio(
  11. BaseOptions(
  12. baseUrl: 'http://localhost:8080/api/v1',
  13. connectTimeout: Durations.short4,
  14. receiveTimeout: Durations.short3,
  15. ),
  16. );
  17. Future<void> fetchData() async {
  18. try {
  19. Response response = await dio.get('http://localhost:8080/api/v1');
  20. print(response.data);
  21. } on DioException catch (e) {
  22. print(e.message);
  23. }
  24. }
  25. Future<void> postData() async {
  26. try {
  27. Response response = await dio.post(
  28. 'http://localhost:8080/api/v1',
  29. data: {'key': 'value'},
  30. );
  31. print(response.data);
  32. } on DioException catch (e) {
  33. print(e.message);
  34. }
  35. }
  36. Future<String> refreshToken() async {
  37. // Perform a request to the refresh token endpoint and return the new access token.
  38. // You can replace this with your own implementation.
  39. return 'your_new_access_token';
  40. }
  41. @override
  42. Widget build(BuildContext context) {
  43. Function(dynamic options, dynamic handler) onRequest;
  44. Future Function(DioException e, dynamic handler) onError;
  45. dio.interceptors.add(
  46. InterceptorsWrapper(
  47. onRequest: onRequest = (options, handler) {
  48. // Add the access token to the request header
  49. options.headers['Authorization'] = 'Bearer your_access_token';
  50. return handler.next(options);
  51. },
  52. onError: onError = (DioException e, handler) async {
  53. if (e.response?.statusCode == 401) {
  54. // If a 401 response is received, refresh the access token
  55. String newAccessToken = await refreshToken();
  56. // Update the request header with the new access token
  57. e.requestOptions.headers['Authorization'] = 'Bearer $newAccessToken';
  58. // Repeat the request with the updated header
  59. return handler.resolve(await dio.fetch(e.requestOptions));
  60. }
  61. return handler.next(e);
  62. },
  63. ),
  64. );
  65. throw UnimplementedError();
  66. }
  67. }