amap_location.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:amap_location/location_option.dart';
  4. import 'package:amap_location/location_result_entity.dart';
  5. import 'package:flutter/services.dart';
  6. // IOS:
  7. // add info.plist GaoDeAppKey
  8. class AmapLocation {
  9. static const MethodChannel _channel = const MethodChannel('amap_location');
  10. static final AmapLocation _instance = AmapLocation();
  11. static AmapLocation get instance => _instance;
  12. StreamController _streamController;
  13. Stream<LocationResultEntity> get locationStream => _streamController.stream;
  14. static Future<String> get platformVersion async {
  15. final String version = await _channel.invokeMethod('getPlatformVersion');
  16. return version;
  17. }
  18. Future<void> startLocation({LocationOption options}) async {
  19. _setLocationCallback();
  20. return await _channel.invokeMethod(
  21. 'startLocation', options?.toMap() ?? LocationOption().toMap());
  22. }
  23. Future<void> disposed() async {
  24. if (!_streamController.isClosed) {
  25. await _streamController.close();
  26. }
  27. _streamController = null;
  28. return await _channel.invokeMethod("closeLocation");
  29. }
  30. void _setLocationCallback() {
  31. if (_streamController == null) {
  32. _streamController = StreamController<LocationResultEntity>.broadcast();
  33. }
  34. _channel.setMethodCallHandler(platformCallHandler);
  35. }
  36. Future<void> platformCallHandler(MethodCall call) async {
  37. try {
  38. if (call.method == "location") {
  39. LocationResultEntity entity =
  40. LocationResultEntity().fromJson(jsonDecode(call.arguments));
  41. _streamController.add(entity);
  42. }
  43. } catch (ex) {
  44. print('Unexpected error: $ex');
  45. }
  46. }
  47. }