905086
2026-11-07 7c8e509c95c2af0c0d076b13fbbc5aa63a06cb69
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
 
class ApiClient {
  static const baseUrl = 'http://localhost:8080';
  static final Dio dio = Dio(BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(minutes: 30),
  ));
 
  static String? token;
 
  static Future<void> init() async {
    final sp = await SharedPreferences.getInstance();
    token = sp.getString('token');
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        if (token != null) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        handler.next(options);
      },
    ));
  }
 
  static Future<void> saveToken(String t) async {
    token = t;
    final sp = await SharedPreferences.getInstance();
    await sp.setString('token', t);
  }
 
  static Future<void> clearToken() async {
    token = null;
    final sp = await SharedPreferences.getInstance();
    await sp.remove('token');
  }
 
  static Future<Map<String, dynamic>> get(String path,
      {Map<String, dynamic>? params}) async {
    final res = await dio.get(path, queryParameters: params);
    return res.data as Map<String, dynamic>;
  }
 
  static Future<Map<String, dynamic>> post(String path,
      [dynamic data]) async {
    final res = await dio.post(path, data: data);
    return res.data as Map<String, dynamic>;
  }
 
  static Future<Map<String, dynamic>> delete(String path) async {
    final res = await dio.delete(path);
    return res.data as Map<String, dynamic>;
  }
}