Flutter iOS应用程序在询问位置时立即崩溃

mftmpeh8  于 2023-06-30  发布在  Flutter
关注(0)|答案(2)|浏览(145)

我只是尝试使用location pub包获取设备的当前位置,但应用程序在运行时崩溃。我确保了Info.plist的所有权限,即

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>...</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>...</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>...</string>
<key>UIBackgroundModes</key>
<string>location</string>

当我从location包调用任何方法时,应用程序立即崩溃。
这是我的实现(直接取自包示例):

// user_location.dart

import 'package:location/location.dart';

class UserLocation {
  Location location = Location();

  late bool _serviceIsEnabled;
  late PermissionStatus _permissionGranted;
  late LocationData _locationData;

  Future<LocationData?> getLocation() async {
    print("Getting location");
   
    _serviceIsEnabled = await location.serviceEnabled(); // crashes right here <-

    if (!_serviceIsEnabled) {
      _serviceIsEnabled = await location.requestService();
      if (!_serviceIsEnabled) return null;
    }

    _permissionGranted = await location.hasPermission();

    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return null;
      }
    }

    _locationData = await location.getLocation();
    return _locationData;
  }
}
// main.dart

Future main() async {
  await dotenv.load();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  LocationData? _userLocation;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() async {
        final location = await UserLocation().getLocation();
        _userLocation = location;
      });
    });
  }

使用Flutterv3.0.5和位置^4.4.0

lf3rwulv

lf3rwulv1#

这个post解决了
只需在Xcode的Signing & Capabilities中启用后台模式>位置更新。

qhhrdooz

qhhrdooz2#

我也有完全相同的问题在我的android应用程序我如何纠正它

相关问题