如何在颤振中正确使用geolocator软件包?

时间:2020-04-12 15:10:29

标签: android flutter dart

我正在使用geolocator软件包在flutter应用程序中获取位置。但是,在应用程序中,有时该应用程序会获得位置并且该应用程序可以正常工作,但有时它根本无法工作,仅存在默认的初始化值。这是服务文件的代码:

import 'package:geolocator/geolocator.dart';
import 'package:geocoder/geocoder.dart';

class Location {
  double latitude;
  double longitude;
  String locationAddress = 'Getting Data';

  Future<void> getLocation() async {
    try {
      Position position = await Geolocator().getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best,
      );
      latitude = position.latitude;
      longitude = position.longitude;
    } catch (e) {
      print(e);
      if (e.code == 'PERMISSION_DENIED') {
        print('denied');
      }
    }
  }

  Future<void> getUserLocation() async {
    //call this async method from whereever you need
    try {
      final coordinates = new Coordinates(latitude, longitude);
      var addresses =
          await Geocoder.local.findAddressesFromCoordinates(coordinates);
      var first = addresses.first;
      locationAddress = first.subLocality + ', ' + first.subAdminArea;
    } catch (e) {
      print(e);
    }
  }
}

这是我要在其中获取locationAddress值的按钮的代码:

class CurrentLocationButton extends StatefulWidget {
  @override
  _CurrentLocationButtonState createState() => _CurrentLocationButtonState();
}

class _CurrentLocationButtonState extends State<CurrentLocationButton> {
  String currentLocation = 'Getting Location';

  @override
  void initState() {
    super.initState();
    getLocationData();
  }

  void getLocationData() async {
    Location location = Location();
    await location.getLocation();
    await location.getUserLocation();
    setState(() {
      currentLocation = location.locationAddress;
    });
  }

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      child: Text(
        'You are in\n$currentLocation',
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 22.0,
          fontWeight: FontWeight.w400,
          color: kWhiteColor,
        ),
      ),
      onPressed: () {},
    );
  }
}

有时,该应用程序可以工作并且位置在按钮文本中,但有时仅文本“获取位置”在那里(这是初始化值)。 我只是希望,一旦应用程序打开,按钮文本中就会出现该位置,如果用户拒绝该权限,则该应用程序应再次请求它。我该怎么做呢?

0 个答案:

没有答案