flutter_sudoku/lib/services/identity_service.dart

80 lines
2.8 KiB
Dart
Raw Permalink Normal View History

2025-11-11 17:45:02 +09:00
import 'dart:convert'; // 👈 [추가]
2025-11-10 18:02:01 +09:00
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
2025-11-11 14:38:15 +09:00
// 앱-고유 ID와 사용자 이름, 레벨 진행 상황을 관리하는 서비스
2025-11-10 18:02:01 +09:00
class IdentityService {
static const String _userIdKey = 'app_user_id';
static const String _userNameKey = 'app_user_name';
2025-11-11 17:45:02 +09:00
static const String _maxLevelKey = 'max_unlocked_level';
// 🔽 [수정] 랭킹 정보를 Map<int, int> 형태로 저장하기 위한 Key
static const String _lastRankMapKey = 'last_checked_rank_map';
2025-11-10 18:02:01 +09:00
// 1. 앱-고유 ID 가져오기 (없으면 생성)
Future<String> getOrCreateUserId() async {
final prefs = await SharedPreferences.getInstance();
String? userId = prefs.getString(_userIdKey);
if (userId == null) {
userId = const Uuid().v4();
await prefs.setString(_userIdKey, userId);
}
return userId;
}
// 2. 랭킹에 등록한 사용자 이름 가져오기
Future<String?> getSavedUserName() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_userNameKey);
}
// 3. 랭킹 등록 성공 시, 사용자 이름 저장하기
Future<void> saveUserName(String name) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_userNameKey, name);
}
2025-11-11 14:38:15 +09:00
2025-11-11 17:45:02 +09:00
// 4. 현재 잠금 해제된 최고 레벨 가져오기
2025-11-11 14:38:15 +09:00
Future<int> getMaxUnlockedLevel() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt(_maxLevelKey) ?? 1;
}
2025-11-11 17:45:02 +09:00
// 5. 새 레벨 잠금 해제
2025-11-11 14:38:15 +09:00
Future<void> saveMaxUnlockedLevel(int level) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_maxLevelKey, level);
}
2025-11-11 17:45:02 +09:00
// 6. 🔽 [수정] 모든 레벨의 랭킹 맵(Map<int, int>) 가져오기
Future<Map<int, int>> getLastSavedRankMap() async {
final prefs = await SharedPreferences.getInstance();
String? jsonString = prefs.getString(_lastRankMapKey);
if (jsonString == null) {
return {}; // 저장된 맵이 없으면 빈 맵 반환
}
try {
// JSON은 Map<String, dynamic>이므로, 키를 int로 변환
final Map<String, dynamic> decodedMap = jsonDecode(jsonString);
return decodedMap.map((key, value) => MapEntry(int.parse(key), value as int));
} catch (e) {
// JSON 파싱 실패 시 빈 맵 반환
return {};
}
}
// 7. 🔽 [수정] 모든 레벨의 랭킹 맵(Map<int, int>) 저장하기
Future<void> saveLastRankMap(Map<int, int> rankMap) async {
final prefs = await SharedPreferences.getInstance();
// JSON 저장을 위해 키를 String으로 변환
final Map<String, int> stringKeyMap =
rankMap.map((key, value) => MapEntry(key.toString(), value));
String jsonString = jsonEncode(stringKeyMap);
await prefs.setString(_lastRankMapKey, jsonString);
}
2025-11-10 18:02:01 +09:00
}