user_model.dart 966 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import 'package:flutter/material.dart';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. import 'package:sport/bean/login.dart';
  4. class UserModel with ChangeNotifier {
  5. User _user = User();
  6. String _token;
  7. User get user => _user;
  8. String get token => _token;
  9. ValueNotifier<int> durationTarget = ValueNotifier(160);
  10. UserModel() {
  11. initUser();
  12. }
  13. /// 初始化 User
  14. Future initUser() async {
  15. SharedPreferences prefs = await SharedPreferences.getInstance();
  16. Map<String, dynamic> map = {};
  17. prefs.getKeys().forEach((element) {
  18. map.putIfAbsent(element, () => prefs.get(element));
  19. });
  20. print(map);
  21. _token = prefs.getString("token");
  22. saveUserInfo(User.fromJson(map));
  23. }
  24. /// 保存用户信息到 sp
  25. saveUserInfo(User user) {
  26. _user = user;
  27. print("User ${_user.gender}");
  28. notifyListeners();
  29. }
  30. saveUserInfoAvator(String avator) {
  31. _user.avatar = avator;
  32. notifyListeners();
  33. }
  34. }