Flutter如何使用geolocator包获取纬度、经度?

标签 flutter dart package

Flutter how to get latitude, longitude using geolocator package? Already gave permissions both android and ios, downloaded package using pubspec.yaml. I don't understand why can't print longitude and latitude to console? tried write 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'),
       ),
     ),
   );
 }
} ```

最佳答案

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

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

方法

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'),
),

关于Flutter如何使用geolocator包获取纬度、经度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66185682/

相关文章:

android - flutter 构建apk文件不能在http请求上工作?

python - -m 开关的目的是什么?

r - 在 R 中使用嵌套 if 评估一系列标准 - 有没有更好的方法?

flutter - 如何为 dart 流添加超时

flutter - 方法 'fromjson' 没有为类型 'type' 定义

flutter - Flutter 是否会在 iOS 中自动显示 Cupertino UI,在 Android 中使用单一代码库显示 Material?

arrays - 如何使用 Dart/Flutter 中的列表从列表中删除重复元素?

javascript - 在 dart 中移植 js 映射

python - 使用共享包部署 python 应用程序

flutter - 如何使用 flutter 文本小部件进行文本换行?