4

I'm simply trying to get the device's current location using the location pub package, however the app is crashing in runtime. I made sure to all the permissions to Info.plist, i.e.

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

The app crashes immediately when I call any method from the location package.

This is my implementation (taken directly from the package examples):


// 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;
      });
    });
  }

Using flutter v3.0.5 and location ^4.4.0

Ryan Roberts
  • 318
  • 1
  • 4
  • 12
  • 2
    And the exception is? – roosi Jul 30 '22 at 08:41
  • 1
    @roosi the terminal just reads `Lost connection to device.`, and a popup from the simulator reads `Runner quit unexpectedly.`. Even when wrapping the location method in a `try/catch`, the simulator crashes. – Ryan Roberts Jul 30 '22 at 08:46

1 Answers1

2

This post solved it

Just had to enable background modes > location updates within Signing & Capabilities in Xcode.

Ryan Roberts
  • 318
  • 1
  • 4
  • 12