profile.dart 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  4. import 'package:json_annotation/json_annotation.dart';
  5. import 'package:e2ee_chat/common/global.dart';
  6. import 'user.dart';
  7. class Profile {
  8. Profile({
  9. this.theme = 0xFF2196F3, this.user, this.isLogin = false, this.isLogout = false,
  10. this.locale = const Locale("zh", "CN")
  11. });
  12. int theme;
  13. User? user;
  14. bool isLogin;
  15. bool isLogout;
  16. Locale locale;
  17. String? get username => user?.username;
  18. Future<String?> get token async {
  19. if (user == null) return null;
  20. final storage = FlutterSecureStorage();
  21. return await storage.read(key: _tokenKey);
  22. }
  23. setToken(String? token) async {
  24. final storage = FlutterSecureStorage();
  25. return await storage.write(key: _tokenKey, value: token);
  26. }
  27. String get _tokenKey => "e2ee_chat token of $username";
  28. factory Profile.fromJson(Map<String, dynamic> json) {
  29. return Profile(
  30. theme: json["theme"],
  31. user: User.fromJson(jsonDecode(json["user"])),
  32. isLogin: json["isLogin"],
  33. isLogout: json["isLogout"],
  34. locale: Locale(json["lang"], json["country"])
  35. );
  36. }
  37. Map<String, dynamic> toJson() => {
  38. "theme": theme,
  39. "user": jsonEncode(user?.toJson()),
  40. "isLogin": isLogin,
  41. "isLogout": isLogout,
  42. "lang": locale.languageCode,
  43. "country": locale.countryCode
  44. };
  45. }