123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import 'package:dio/dio.dart';
- import 'package:flutter/material.dart';
- class DioPage extends StatefulWidget {
- @override
- State<StatefulWidget> createState() {
- return _DioPageState();
- }
- }
- class _DioPageState extends State<DioPage> {
- Dio dio = Dio(
- BaseOptions(
- baseUrl: 'http://localhost:8080/api/v1',
- connectTimeout: Durations.short4,
- receiveTimeout: Durations.short3,
- ),
- );
- Future<void> fetchData() async {
- try {
- Response response = await dio.get('http://localhost:8080/api/v1');
- print(response.data);
- } on DioException catch (e) {
- print(e.message);
- }
- }
- Future<void> postData() async {
- try {
- Response response = await dio.post(
- 'http://localhost:8080/api/v1',
- data: {'key': 'value'},
- );
- print(response.data);
- } on DioException catch (e) {
- print(e.message);
- }
- }
- Future<String> refreshToken() async {
- // Perform a request to the refresh token endpoint and return the new access token.
- // You can replace this with your own implementation.
- return 'your_new_access_token';
- }
- @override
- Widget build(BuildContext context) {
- Function(dynamic options, dynamic handler) onRequest;
- Future Function(DioException e, dynamic handler) onError;
- dio.interceptors.add(
- InterceptorsWrapper(
- onRequest: onRequest = (options, handler) {
- // Add the access token to the request header
- options.headers['Authorization'] = 'Bearer your_access_token';
- return handler.next(options);
- },
- onError: onError = (DioException e, handler) async {
- if (e.response?.statusCode == 401) {
- // If a 401 response is received, refresh the access token
- String newAccessToken = await refreshToken();
- // Update the request header with the new access token
- e.requestOptions.headers['Authorization'] = 'Bearer $newAccessToken';
- // Repeat the request with the updated header
- return handler.resolve(await dio.fetch(e.requestOptions));
- }
- return handler.next(e);
- },
- ),
- );
- throw UnimplementedError();
- }
- }
|