user_model.dart 1019 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. clear(){
  35. _user = null;
  36. _token = null;
  37. }
  38. }