Initial commit
This commit is contained in:
58
lib/services/storage_service.dart
Normal file
58
lib/services/storage_service.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'dart:convert';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../models/user.dart';
|
||||
|
||||
class StorageService {
|
||||
static final StorageService _instance = StorageService._internal();
|
||||
factory StorageService() => _instance;
|
||||
StorageService._internal();
|
||||
|
||||
Box? _box;
|
||||
SharedPreferences? _prefs;
|
||||
|
||||
Future<void> init() async {
|
||||
_box = Hive.box('zhinianBox');
|
||||
_prefs = await SharedPreferences.getInstance();
|
||||
}
|
||||
|
||||
Future<void> saveUser(User user) async {
|
||||
await _box?.put('user', jsonEncode(user.toJson()));
|
||||
}
|
||||
|
||||
User? getUser() {
|
||||
final data = _box?.get('user');
|
||||
if (data == null) return null;
|
||||
try {
|
||||
return User.fromJson(jsonDecode(data));
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clearUser() async {
|
||||
await _box?.delete('user');
|
||||
}
|
||||
|
||||
Future<void> setString(String key, String value) async {
|
||||
await _prefs?.setString(key, value);
|
||||
}
|
||||
|
||||
String? getString(String key) {
|
||||
return _prefs?.getString(key);
|
||||
}
|
||||
|
||||
Future<void> setBool(String key, bool value) async {
|
||||
await _prefs?.setBool(key, value);
|
||||
}
|
||||
|
||||
bool? getBool(String key) {
|
||||
return _prefs?.getBool(key);
|
||||
}
|
||||
|
||||
Future<void> remove(String key) async {
|
||||
await _prefs?.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
final storageService = StorageService();
|
||||
Reference in New Issue
Block a user