Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.github.com> Co-authored-by: eddgranados12 <eddgranados12@users.noreply.github.com> vistas de mockup actualizaco
53 lines
1.5 KiB
Dart
53 lines
1.5 KiB
Dart
// lib/core/dio_client.dart
|
|
// Cliente HTTP configurado con base URL, interceptor de JWT y timeouts.
|
|
|
|
import 'package:dio/dio.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
|
|
// La base URL viene de las variables de entorno en flutter_dotenv o dart-define.
|
|
// Para el emulador Android: http://10.0.2.2:8000
|
|
// Para producción: https://tu-backend.run.app
|
|
const String _kBaseUrl = String.fromEnvironment(
|
|
'API_BASE_URL',
|
|
defaultValue: 'http://10.0.2.2:8000',
|
|
);
|
|
|
|
// Token JWT — se rellena desde el provider de auth tras login
|
|
String? _jwtToken;
|
|
|
|
void setJwtToken(String token) => _jwtToken = token;
|
|
void clearJwtToken() => _jwtToken = null;
|
|
|
|
Dio _buildDio() {
|
|
final dio = Dio(
|
|
BaseOptions(
|
|
baseUrl: _kBaseUrl,
|
|
connectTimeout: const Duration(seconds: 10),
|
|
receiveTimeout: const Duration(seconds: 15),
|
|
headers: {'Content-Type': 'application/json'},
|
|
),
|
|
);
|
|
|
|
// Interceptor: adjunta JWT en cada petición
|
|
dio.interceptors.add(
|
|
InterceptorsWrapper(
|
|
onRequest: (options, handler) {
|
|
if (_jwtToken != null) {
|
|
options.headers['Authorization'] = 'Bearer $_jwtToken';
|
|
}
|
|
handler.next(options);
|
|
},
|
|
onError: (error, handler) {
|
|
// 401 → limpiar token (el router de go_router redirige al login)
|
|
if (error.response?.statusCode == 401) {
|
|
clearJwtToken();
|
|
}
|
|
handler.next(error);
|
|
},
|
|
),
|
|
);
|
|
|
|
return dio;
|
|
}
|
|
|
|
final dioProvider = Provider<Dio>((ref) => _buildDio()); |