【问题标题】:Can't Load Current location in Flutter application无法在 Flutter 应用程序中加载当前位置
【发布时间】:2019-07-03 17:20:16
【问题描述】:

我正在使用地理定位器插件并获取当前的纬度和经度,但我无法在我的 Flutter 应用程序的 initstate 中加载它。 它显示渲染错误。

void initState() {
// TODO: implement initState
super.initState();
getCurrentLocation();

}

void getCurrentLocation() async {
var answer = await Geolocator().getCurrentPosition();
setState(() {
  latitude = answer.latitude;
  longitude = answer.longitude;
});

}

地图在几毫秒后更新为当前位置,但显示这些错误。 I/flutter (14143):══╡小部件库发现异常╞═════════════════════════════════════════════ ═════════════════════════

I/flutter (14143):在构建 HomePage(dirty, state: _HomePageState#d55de) 时抛出了以下断言:

I/flutter (14143): 'package:google_maps_flutter/src/location.dart': 断言失败: line 17 pos 16: 'latitude !=

I/flutter (14143): null': 不正确。

我/颤动(14143):

I/flutter (14143):要么断言表明框架本身有错误,要么我们应该提供大量

I/flutter (14143):此错误消息中的更多信息可帮助您确定和修复根本原因。

I/flutter (14143):无论哪种情况,请通过在 GitHub 上提交错误来报告此断言:

【问题讨论】:

    标签: google-maps flutter dart


    【解决方案1】:

    按照 Abbas.M 的建议,我正在使用 FutureBuilder Widget 解决我的问题。

    FutureBuilder 小部件: https://www.youtube.com/watch?v=ek8ZPdWj4Qo

    我声明变量_future

    Future<Position> _future;
    

    我在 initState 中调用我的异步方法

    void initState() {
    // TODO: implement initState
    super.initState();
    _future = getCurrentLocation();
    }
    

    使用 FutureBuilder 小部件解决了我的问题,我将异步函数返回值传递给 FutureBuilder 小部件的参数。

    此条件 if(snapshot.connectionState == ConnectionState.done) 有助于找到我们的异步函数是否已完成并返回值。如果它处于 Done 状态,则表示功能已完成并返回。

    如果不满足该条件,则表示异步功能未完成,因此我使用 CircularProgressIndicator 小部件通知用户了解应用正在加载。

    Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Flutter Krish"),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (!snapshot.hasError) {
                  print(snapshot.data.latitude);
                  return Stack(children: <Widget>[
                    GoogleMap(
                      initialCameraPosition: CameraPosition(
                          target: LatLng(
                              snapshot.data.latitude, snapshot.data.longitude),
                          zoom: 12.0),
                      onMapCreated: mapCreated,
                    ),
                    Positioned(
                      top: 30.0,
                      left: 15.0,
                      right: 15.0,
                      child: Container(
                        height: 50.0,
                        width: double.infinity,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.white),
                        child: TextField(
                          decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: 'Enter Address',
                              contentPadding:
                                  EdgeInsets.only(top: 15.0, left: 15.0),
                              suffixIcon: IconButton(
                                icon: Icon(Icons.search),
                                onPressed: searchAndNavigate,
                                iconSize: 30.0,
                              )),
                          onChanged: (value) {
                            searchAddress = value;
                          },
                        ),
                      ),
                    ),
                  ]);
                }
              } else {
                return Center(child: CircularProgressIndicator());
              }
            }));
    }
    
    Future<Position> getCurrentLocation() async
    {
    var answer = await Geolocator().getCurrentPosition();
    return answer;
    }
    

    【讨论】:

      【解决方案2】:

      我尝试了很多方法,直到我找到了这个方法,这要感谢一个帮助另一个颤振 facebook 小组的好心人。确保在 pubspec.yaml 中将位置更新到最新版本

      依赖: 地点:^2.3.5 然后改成如下代码:

       
        LocationData _currentLocation;
        StreamSubscription<LocationData> _locationSubscription;
      
        var _locationService = new Location();
        String error;
      
        void initState() {
          super.initState();
      
          initPlatformState();
      
          _locationSubscription = _locationService
              .onLocationChanged()
              .listen((LocationData currentLocation) async {
            setState(() {
              _currentLocation = currentLocation;
            });
          });
        }
      
        void initPlatformState() async {
          try {
            _currentLocation = await _locationService.getLocation();
      
      
          } on PlatformException catch (e) {
            if (e.code == 'PERMISSION_DENIED') {
              error = 'Permission denied';
            }else if(e.code == "PERMISSION_DENIED_NEVER_ASK"){
              error = 'Permission denied';
            }
            _currentLocation = null;
          }
       Run code snippetReturn to post

      您可以访问经度和纬度为

      _currentLocation.longitude 和 _currentLocation.latitude

      这些将返回双精度值。此外,https://pub.dev/packages/location#-readme-tab- 上还有更多选择

      【讨论】:

      • 感谢您的支持兄弟,我通过使用 FutureBuilder 小部件解决了我的应用程序错误。
      • 您能否在此处发布您的解决方案,以便对其他人有所帮助
      【解决方案3】:

      我几乎不知道发生了什么,但基于代码,因为您有一个 .then,在 .then 函数发生之前,您的纬度和经度为空,当您有一个 .then 时,其余代码不会等待为将来解决。尝试在初始化状态中将经度和纬度初始化为 null 以外的某个值,这样:

      void initState() {
      // TODO: implement initState
      super.initState();
      latitude = 0;
      longitude = 0;
      getCurrentLocation().then((k) {
        latitude = k.latitude;
        longitude = k.longitude;
        setState(() {});
        });
      }
      

      【讨论】:

      • 我尝试过您的建议,但它只加载 0,0,而不是更新当前位置。现在我更改了我的代码,现在首先我的应用程序屏幕显示错误,几毫秒后显示当前位置的地图。
      • 那是因为你必须在 .then 完成后再次设置状态
      • 只需在 .then 方法的最后一行添加setState(() {});
      • 兄弟,我按照您的建议更改了我的代码,但地图加载初始值为 0,0,并且未更新 UI 中的当前位置。但我有问题的代码最初出现错误,但几毫秒后,它会更新 UI 中的当前位置
      • 您最初遇到的错误是因为纬度和经度设置为 0 时正在使用它们。错误消失是因为过了一会儿您的 getCurrentLocation() 解决了并且它们有值而不是保持为空。如果你想避免这些东西,你应该研究 FutureBuilder。查看this
      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 2020-11-15
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多