amap_location.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. class AmapLocation {
  7. static const MethodChannel _channel = const MethodChannel('amap_location');
  8. static final AmapLocation _instance = AmapLocation();
  9. static AmapLocation get instance => _instance;
  10. StreamController _streamController;
  11. Stream<LocationResultEntity> get locationStream => _streamController.stream;
  12. static Future<String> get platformVersion async {
  13. final String version = await _channel.invokeMethod('getPlatformVersion');
  14. return version;
  15. }
  16. Future<void> startLocation({LocationOption options}) async {
  17. _setLocationCallback();
  18. return await _channel.invokeMethod(
  19. 'startLocation', options?.toMap() ?? LocationOption().toMap());
  20. }
  21. Future<void> disposed() async {
  22. if (!_streamController.isClosed) {
  23. await _streamController.close();
  24. }
  25. _streamController = null;
  26. return await _channel.invokeMethod("closeLocation");
  27. }
  28. void _setLocationCallback() {
  29. if (_streamController == null) {
  30. _streamController = StreamController<LocationResultEntity>.broadcast();
  31. }
  32. _channel.setMethodCallHandler(platformCallHandler);
  33. }
  34. Future<void> platformCallHandler(MethodCall call) async {
  35. try {
  36. if (call.method == "location") {
  37. LocationResultEntity entity =
  38. LocationResultEntity().fromJson(jsonDecode(call.arguments));
  39. _streamController.add(entity);
  40. }
  41. } catch (ex) {
  42. print('Unexpected error: $ex');
  43. }
  44. }
  45. }