【问题标题】:Flutter how to get latitude, longitude using geolocator package?Flutter如何使用geolocator包获取纬度、经度?
【发布时间】:2021-05-17 00:29:46
【问题描述】:

Flutter 如何使用 geolocator 包获取纬度、经度? 已经授予 android 和 ios 的权限,使用 pubspec.yaml 下载包。我不明白为什么不能将经度和纬度打印到控制台?试过写 print(position), print(position.longitude()), print(position.latitue()).

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';


class LoadingScreen extends StatefulWidget {
 @override
 _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
 void getLocation() async {
   print('Printing text before getCurrentLocation()');
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
   print(position);


}

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: Center(
       child: RaisedButton(
         color: Colors.red,
         onPressed: () {
           getLocation();
         },
         child: Text('Get Location'),
       ),
     ),
   );
 }
} ```

【问题讨论】:

    标签: flutter dart package


    【解决方案1】:

    应该是position.latitudeposition.longitude。您使用了position.longitude() & position.latitude(),这是不正确的。

    另外,您需要为onPressed 回调添加async-await。我假设您已经在清单中添加了权限并授予了必要的权限。

    方法

    void getLocation() async {
       Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
       print(position.latitude);
       print(position.longitude);
    }
    

    小部件

    RaisedButton(
        color: Colors.red,
        onPressed: () async {
            await getLocation();
        },
        child: Text('Get Location'),
    ),
    

    【讨论】:

    • 谢谢你添加异步后,等待 onPressed。一切正常。
    • 太棒了!我很高兴能帮上忙。如果它回答了您的问题,您可以将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多