【问题标题】:Flutter - Location package showing address in Emulator but not in real deviceFlutter - 位置包在模拟器中显示地址但不在真实设备中
【发布时间】:2021-07-19 11:14:12
【问题描述】:

这是我用过的包:location

我的提供者类

class LocationProvider with ChangeNotifier {
  LocationData? _currentPosition;
  Location? location = Location();
  List<geo.Placemark>? placemarks;

  String? street;
  String? locality;
  String? country;

  getLocation() async {
    print('getLocation() was called');
    _currentPosition = await location!.getLocation();

    print('Current Position: $_currentPosition');

    placemarks = await geo.placemarkFromCoordinates(
      _currentPosition!.latitude!,
      _currentPosition!.longitude!,
    );

    print('Placemarks: $placemarks');

    street = placemarks?[0].street;
    locality = placemarks?[0].locality;
    country = placemarks?[0].country;

    notifyListeners();
  }
}

这在模拟器上可以正常工作。但在实际设备中,它在我使用这些变量的地方显示为 null。

在我的控制台中,我只看到getLocation() was called,但其他数据没有打印在我的控制台中。

这是在所需小部件的 build() 中调用它的方式

final locationDetail = Provider.of<LocationProvider>(context, listen: false);

我在 android>app>src>main>AndroidManifest.xml 文件中添加了以下权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

以上代码在模拟器中有效,但在真实设备中无效。

【问题讨论】:

  • 能否确认设备的API级别?
  • 我设备的API级别是30。

标签: flutter dart flutter-layout fluttermap


【解决方案1】:

我在提供程序类中添加了以下代码行。之前它在其他文件中。

_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;
  }
}

以上几行是之前添加的

_currentPosition = await location!.getLocation();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多