无法在 Flutter 中获取用户的位置

Unable to get user's location in Flutter

请帮忙,我无法获取用户的位置: 想象一下我有一个像这样的小部件:

 Text('LAT: ${_currentPosition?.altitude ?? "na"}'),
            Text('LNG: ${_currentPosition?.longitude ?? "na"}'),
            Text('ADDRESS: ${_currentAddress ?? "na"}'),
            const SizedBox(height: 32),
            ElevatedButton(
              onPressed: _getCurrentPosition,
              child: const Text("Get Current Location"),

以及通过图书馆获取位置的逻辑:

  Future<bool> _handleLocationPermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text(
              'Location services are disabled. Please enable the services')));
      return false;
    }
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Location permissions are denied')));
        return false;
      }
    }
    if (permission == LocationPermission.deniedForever) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text(
              'Location permissions are permanently denied, we cannot request permissions.')));
      return false;
    }
    return true;
  }

  Future<void> _getCurrentPosition() async {
    final hasPermission = await _handleLocationPermission();

    if (!hasPermission) return;
    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) {
      setState(() => _currentPosition = position);
      _getAddressFromLatLng(_currentPosition!);
    }).catchError((e) {
      debugPrint(e);
    });
  }

  Future<void> _getAddressFromLatLng(Position position) async {
    await placemarkFromCoordinates(position.latitude, position.longitude)
        .then((List<Placemark> placemarks) {
      Placemark place = placemarks[0];
      setState(() {
        _currentAddress =
            '${place.street}, ${place.subLocality}, ${place.subAdministrativeArea}, ${place.postalCode}';
      });
    }).catchError((e) {
      debugPrint(e);
    });
  }

在 StatefulWidget 中。 我目前没有从中得到任何东西而且我不明白,因为我完全按照本教程进行操作:

https://medium.com/@fernnandoptr/how-to-get-users-current-location-address-in-flutter-geolocator-geocoding-be563ad6f66a

------------编辑------------

我尝试用位置包实现这个:

Location location = Location();
late bool _serviceEnabled;
late PermissionStatus _permissionGranted;
late LocationData _locationData;
late double? fieldLatitude;
late double? fieldLogitude;

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

    getfieldlocation();
  }

  Future<void> getfieldlocation() async {
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
    _locationData = await location.getLocation();
    setState(() {
       fieldLatitude = _locationData.latitude;
       fieldLogitude = _locationData.longitude;
      print(fieldLatitude);print(fieldLogitude);
    });
  }

但它给我一个与初始化变量相关的错误“Field fieldLatitude 尚未初始化”

我明白你的问题。在我的项目中,我使用 https://pub.dev/packages/location 包。获取位置的步骤。

Future<void> getfieldlocation() async {
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
    _locationData = await location.getLocation();
    setState(() {
      fieldLatitude = _locationData.latitude;
      fieldLogitude = _locationData.longitude;
      print(fieldLatitude);print(fieldLogitude);
    });
  }

我在 initstate() 函数中调用了它,它只在开始时调用。 如果你想连续调用它 使用 setduration 函数。

如果有用别忘了投稿,有疑惑也请回复。 祝你有美好的一天:)