You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Location插件在iOS模拟器自定义位置下无法获取位置数据

问题

开发一款需要获取位置数据的Flutter应用,采用Geolocator和Location插件获取用户坐标。在iOS模拟器中,将位置设置为「Custom Location」时,location.getLocation()方法无法执行完成;但设置为「Apple」这类预定义位置时可正常工作。

完整代码如下:

import 'package:flutter/material.dart';
import 'package:location/location.dart' as loc;
import 'package:geocoding/geocoding.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    location();
    super.initState();
  }

  String? _city;
  String? _country;

  Future<void> location() async {
    loc.Location location = loc.Location();

    bool serviceEnabled;
    loc.PermissionStatus permissionGranted;
    loc.LocationData? locationData;

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

    permissionGranted = await location.hasPermission();
    if (permissionGranted == loc.PermissionStatus.denied) {
      permissionGranted = await location.requestPermission();
      if (permissionGranted != loc.PermissionStatus.granted) {
        return;
      }
    }
    print('gets always printed');
    locationData = await location.getLocation();
    print('This is not getting printed when location is set on "Custom Location"');
    print(locationData);

    List<Placemark> placemarks = await placemarkFromCoordinates(
        locationData.latitude!, locationData.longitude!);

    setState(() {
      _city = placemarks[0].locality!;
      _country = placemarks[0].country!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: const Text('Location'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Coordinates:', style: TextStyle(fontSize: 20)
            ),
            Column(
              children: [
                Text("$_city, $_country", style: const TextStyle(fontSize: 30),)
              ],
            ),
          ],
        ),
      ),
    );
  }
}

解决方案

1. 验证自定义坐标合法性

确保输入的自定义经纬度在有效范围内:纬度需介于-90°到90°之间,经度介于-180°到180°之间。无效坐标会导致Location插件无法解析并返回数据。

2. 手动触发位置更新

iOS模拟器设置自定义位置后,可能需要重新触发位置同步:

  • 打开模拟器菜单 Debug > Location > Custom Location,重新输入坐标并确认;
  • 或者切换到其他预设位置再切回自定义位置,强制刷新位置数据。

3. 排查插件冲突

同时使用Geolocator和Location两个位置插件可能存在底层冲突,建议单独使用Geolocator测试:
替换原location.getLocation()为Geolocator的方法:

import 'package:geolocator/geolocator.dart';

// ...

Position position = await Geolocator.getCurrentPosition(
  desiredAccuracy: LocationAccuracy.high,
);
print('Latitude: ${position.latitude}, Longitude: ${position.longitude}');

4. 升级Location插件版本

旧版本的Location插件对iOS模拟器自定义位置的支持存在bug,前往pubspec.yaml将插件版本更新至最新稳定版后执行flutter pub get。

5. 添加错误捕获排查问题

在location.getLocation()周围添加try-catch块,打印具体错误信息,定位问题根源:

print('gets always printed');
try {
  locationData = await location.getLocation();
  print('Location data retrieved: $locationData');
  print('This should print now with custom location');
} catch (e, stackTrace) {
  print('Error fetching location: $e');
  print('Stack trace: $stackTrace');
}

内容的提问来源于stack exchange,提问作者fxruk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:35:13