如何检查 Flutter 中是否启用了位置和互联网服务并检索其当前状态?

问题描述 投票:0回答:1

我需要确保在应用程序使用过程中启用用户的位置和互联网。

虽然我已经使用 internet_connection_checker_plus 包成功实现了连接检查,但在使用 GeoLocator 动态检查位置服务的状态方面面临着挑战。是否有一个包或方法可以让我有效地检查和管理位置和互联网服务? 如果没有,如何使用 GeoLocator 动态跟踪定位服务的实时状态以确定其处于活动状态还是非活动状态?

flutter location internet-connection geolocator
1个回答
0
投票

您可以使用 Geolocator 文档

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

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition();
  }

使用 Riverpod,您可以声明一个提供商来检查许可状态

final locationProvider = FutureProvider<Position>((ref) async {
  final controller = ref.read(locationControllerProvider);
  return await controller.getUserLocation();
});

然后在您的构建方法中,您可以观察此提供程序并对状态更改做出反应

Widget build(BuildContext context) {
    final locationCheck = ref.watch(locationProvider);
    return Scaffold(
      body: locationCheck.when(
        data: (locationData) {
          //use location
        },
        loading: () => LoaderWidget(),
        error: (error, stackTrace) {
          // message to the user that location permission is disable
        },
      ),
    );
  }

如果你需要实时,你可以使用 StreamProvider 而不是 FutureProvider

© www.soinside.com 2019 - 2024. All rights reserved.