app.dart 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import 'dart:io';
  2. import 'package:amap_flutter_location/amap_flutter_location.dart';
  3. import 'package:farmer_client/models/entities/person.dart';
  4. import 'package:farmer_client/widgets/Modal.dart';
  5. import 'package:get/get.dart';
  6. import 'package:get_storage/get_storage.dart';
  7. import '../services/user.dart';
  8. import '../utils/location.dart';
  9. class AppController extends GetxController {
  10. // 有了这句, 可以直接 AppController.t 调用
  11. static AppController t = Get.find();
  12. GetStorage box = GetStorage();
  13. final user = Rx<Person>(Person());
  14. final location = Rxn<Map<String, Object>>();
  15. final testInt = 1.obs;
  16. AMapFlutterLocation? _location;
  17. get locationStr {
  18. if (null == location.value) return null;
  19. // 不知道什么问题, 模拟器中 lng 是负值
  20. String longitude = location.value!['longitude'] as String;
  21. String latitude = location.value!['latitude'] as String;
  22. return longitude.toString() + "," + latitude.toString();
  23. }
  24. void onLocationChange(Map<String, Object> result) {
  25. location(result);
  26. }
  27. @override
  28. void onInit() {
  29. super.onInit();
  30. // 尝试获取 location
  31. requireLocation(onLocationChange).then((loc) {
  32. _location = loc;
  33. }).catchError((e) {
  34. print(e);
  35. showAlert(
  36. title: '获取定位失败',
  37. message: e.message,
  38. onConfirm: () => exit(1),
  39. );
  40. });
  41. var route = Get.routing;
  42. if (box.read('token') != null) {
  43. // 尝试获取一次人员信息
  44. getCurrent().then((person) {
  45. Person p = Person.fromJson(person);
  46. user(p);
  47. box.write("user", p);
  48. }).catchError((e) {
  49. box.remove("token");
  50. print(e);
  51. });
  52. }
  53. }
  54. @override
  55. void onClose() {
  56. if (null != _location) {
  57. _location?.destroy();
  58. }
  59. }
  60. }