user_model.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'package:flutter/material.dart';
  2. import 'package:provider/provider.dart';
  3. import 'package:shared_preferences/shared_preferences.dart';
  4. import 'package:sport/application.dart';
  5. import 'package:sport/bean/login.dart';
  6. import 'package:sport/bean/sport_detail.dart';
  7. import 'package:sport/provider/bluetooth.dart';
  8. import 'package:sport/router/navigator_util.dart';
  9. import 'package:sport/utils/sport_utils.dart';
  10. class UserModel with ChangeNotifier {
  11. User _user = User();
  12. String? _token;
  13. User get user => _user;
  14. String get token => _token ?? "";
  15. double latitude = 0, longitude = 0;
  16. ValueNotifier<int> durationTarget = ValueNotifier(160);
  17. ValueNotifier<int> runUserCount = ValueNotifier(0);
  18. UserModel() {
  19. initUser();
  20. }
  21. /// 初始化 User
  22. Future initUser() async {
  23. SharedPreferences prefs = await SharedPreferences.getInstance();
  24. Map<String, dynamic> map = {};
  25. prefs.getKeys().forEach((element) {
  26. map.putIfAbsent(element, () => prefs.get(element));
  27. });
  28. print(map);
  29. _token = prefs.getString("token");
  30. saveUserInfo(User.fromJson(map));
  31. if (prefs.containsKey("run_latitude")) {
  32. latitude = prefs.getDouble("run_latitude") ?? 0;
  33. longitude = prefs.getDouble("run_longitude") ?? 0;
  34. }
  35. }
  36. /// 保存用户信息到 sp
  37. saveUserInfo(User user) {
  38. _user = user;
  39. // print("User ${_user.gender}");
  40. weight = user.weight ?? 60.0;
  41. gender = user.gender ?? 0;
  42. notifyListeners();
  43. }
  44. saveUserInfoAvator(String avator) {
  45. _user.avatar = avator;
  46. notifyListeners();
  47. }
  48. clear() {
  49. _token = null;
  50. }
  51. logout(BuildContext context) async {
  52. clear();
  53. SharedPreferences prefs = await SharedPreferences.getInstance();
  54. prefs.clear();
  55. Provider.of<Bluetooth>(context, listen: false).clearDevice(deleteStep: true);
  56. NavigatorUtil.goLogin(context);
  57. }
  58. Future<String> sport(RecordsTodaySum? item) async {
  59. SharedPreferences prefs = await SharedPreferences.getInstance();
  60. int type = prefs.getInt("sport_type") ?? 0;
  61. int consume = item?.consume ?? 0;
  62. if((item?.consume_jog ?? 0) > 0 && type == 0){
  63. consume -= item?.consume_jog ?? 0;
  64. return SportUtils.calSportStr(type, SportUtils.calSportTypeData(type, consume, _user.weight ?? weight) + (item?.distance_jog ?? 0) / 1000.0);
  65. }else {
  66. return SportUtils.calSportType(type, consume, _user.weight ?? weight);
  67. }
  68. }
  69. }