Ryan Roberts
Ryan Roberts

Reputation: 357

Flutter iOS App Crashes Immediately when asking for location

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

Upvotes: 4

Views: 2690

Answers (1)

Ryan Roberts
Ryan Roberts

Reputation: 357

This post solved it

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

Upvotes: 2

Related Questions