import 'package:shared_preferences/shared_preferences.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; class AuthService extends ChangeNotifier { static const String _tokenKey = 'auth_token'; static const String _userKey = 'user_info'; String? _token; String? _userId; String? _userName; bool _isAuthenticated = false; bool _isLoading = false; final Dio _dio = Dio(); String? get token => _token; String? get userId => _userId; String? get userName => _userName; bool get isAuthenticated => _isAuthenticated; bool get isLoading => _isLoading; AuthService() { _dio.options.baseUrl = 'http://your-api-domain.com/api'; _dio.interceptors.add( InterceptorsWrapper( onRequest: (options, handler) { if (_token != null) { options.headers['Authorization'] = 'Bearer $_token'; } handler.next(options); }, ), ); } Future init() async { await loadStoredAuth(); } Future loadStoredAuth() async { try { final prefs = await SharedPreferences.getInstance(); final token = prefs.getString(_tokenKey); final userJson = prefs.getString(_userKey); if (token != null && userJson != null) { _token = token; _parseUserInfo(userJson); _isAuthenticated = true; } } catch (e) { print('加载认证信息失败: $e'); } notifyListeners(); } void _parseUserInfo(String userJson) { try { // 这里解析用户信息,根据实际的API响应格式 final user = userJson; _userId = 'user_id_from_json'; // 从JSON解析 _userName = 'username_from_json'; // 从JSON解析 } catch (e) { print('解析用户信息失败: $e'); } } Future login(String username, String password) async { _isLoading = true; notifyListeners(); try { final response = await _dio.post('/auth/login', data: { 'username': username, 'password': password, }); if (response.statusCode == 200) { final data = response.data; _token = data['token']; _userId = data['user_id']; _userName = data['username']; _isAuthenticated = true; // 保存到本地存储 final prefs = await SharedPreferences.getInstance(); await prefs.setString(_tokenKey, _token!); await prefs.setString(_userKey, data.toString()); notifyListeners(); return true; } else { throw Exception('登录失败'); } } catch (e) { print('登录错误: $e'); return false; } finally { _isLoading = false; notifyListeners(); } } Future logout() async { try { // 调用登出API await _dio.post('/auth/logout'); } catch (e) { print('登出API调用失败: $e'); } // 清除本地数据 _token = null; _userId = null; _userName = null; _isAuthenticated = false; final prefs = await SharedPreferences.getInstance(); await prefs.remove(_tokenKey); await prefs.remove(_userKey); notifyListeners(); } }