user_model.dart 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'package:dio/dio.dart';
  2. import 'package:e2ee_chat/common/global.dart';
  3. import 'package:e2ee_chat/common/api.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:provider/provider.dart';
  6. import 'profile.dart';
  7. class UserModel extends ProfileChangeNotifier {
  8. /*
  9. UserModel._();
  10. static UserModel _instance = UserModel._();
  11. factory UserModel() => _instance!;
  12. */
  13. // TODO: online keep status; A logout, B logout?
  14. bool get isLogin => profile.isLogin;
  15. Future<bool> login({String? username, String? password}) async {
  16. debug('UserModel login begin');
  17. profile.username = username ?? profile.username;
  18. bool _result = false;
  19. String? token = await profile.token;
  20. if (profile.username != null && (password != null || token != null)) {
  21. String? _token;
  22. try {
  23. _token = await Api().login(username: profile.username!, password: password, token: token);
  24. _result = _token != null;
  25. } on DioError catch(e) {
  26. print(e);
  27. }
  28. profile.setToken(_token);
  29. debug('UserModel login get token: ${await profile.token}');
  30. if (await profile.token != null) {
  31. debug('UserModel login success!');
  32. profile.isLogin = true;
  33. profile.isLogout = false;
  34. notifyListeners();
  35. }
  36. }
  37. debug('UserModel login end');
  38. return _result;
  39. }
  40. Future<void> logout() async {
  41. if (profile.isLogin && await Api().logout()) {
  42. profile.isLogin = false;
  43. profile.isLogout = true;
  44. notifyListeners();
  45. }
  46. }
  47. }