ar_tourism_flutter_unity/lib/providers/auth_provider.dart
2025-05-14 17:04:13 +08:00

68 lines
2.1 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthProvider with ChangeNotifier {
String? _token;
String? _userId;
bool _isLoggedIn = false;
static const String _tokenKey = 'auth_token';
static const String _userIdKey = 'user_id';
String? get token => _token;
String? get userId => _userId;
bool get isLoggedIn => _isLoggedIn;
AuthProvider() {
// 初始化时设置登录状态,避免覆盖外部设置的值
_isLoggedIn = _token != null;
}
// 改为公开方法
Future<void> loadTokenFromPrefs() async {
// 如果已经有token不要再从SharedPreferences加载
if (_token != null) return;
final prefs = await SharedPreferences.getInstance();
_token = prefs.getString(_tokenKey) ?? prefs.getString('token');
_userId = prefs.getString(_userIdKey) ?? prefs.getString('userId');
_isLoggedIn = _token != null;
notifyListeners();
}
Future<void> setToken(String? token, {String? userId}) async {
_token = token;
_userId = userId;
_isLoggedIn = token != null;
notifyListeners();
await _saveTokenToPrefs(token, userId: userId);
}
Future<void> clearToken() async {
_token = null;
_userId = null;
_isLoggedIn = false;
notifyListeners();
await _saveTokenToPrefs(null);
}
Future<void> _saveTokenToPrefs(String? token, {String? userId}) async {
final prefs = await SharedPreferences.getInstance();
if (token != null) {
await prefs.setString(_tokenKey, token);
await prefs.setString('token', token); // 兼容旧键名
if (userId != null) {
await prefs.setString(_userIdKey, userId);
await prefs.setString('userId', userId); // 兼容旧键名
}
// 同时设置登录状态标志
await prefs.setBool('isLoggedIn', true);
} else {
await prefs.remove(_tokenKey);
await prefs.remove(_userIdKey);
await prefs.remove('token');
await prefs.remove('userId');
// 清除登录状态标志
await prefs.setBool('isLoggedIn', false);
}
}
}