无法在Flutter应用程序中加载当前位置 [英] Can't Load Current location in Flutter application

查看:271
本文介绍了无法在Flutter应用程序中加载当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用geolocator插件并获取当前的纬度和经度,但无法在Flutter应用程序的初始状态下加载它。
显示呈现错误。

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

}

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

}



地图已更新为毫秒后显示当前位置,但显示这些错误。
I / flutter(14143):W小工具库引起的异常CA ═════════════════════════════



I /颤振(14143) :构建HomePage(脏,状态:_HomePageState#d55de)时引发了以下断言:



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



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



I / flutter(14143):



I / flutter(14143):要么断言表明框架本身有错误,要么应该实质性地提供



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



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

解决方案

作为Abbas.M的建议,我正在使用FutureBuilder小部件解决我的问题。



FutureBuild er小工具:
https://www.youtube.com/watch?v=ek8ZPdWj4Qo



我在声明变量_future

  Future< ; Position> _未来; 

我在initState中调用异步方法

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

使用FutureBuilder小部件解决了我的问题,并通过了异步函数返回



此条件if(snapshot.connectionState == ConnectionState.done)有助于查找异步函数是否完成并返回值。如果处于未完成状态,则表示函数已完成并返回。



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

 小部件build(BuildContext context){
return Scaffold(
appBar:AppBar(
标题:Text( Flutter Krish),
),
正文:FutureBuilder(
future:_future,
builder:(context,快照){
if(snapshot.connectionState == ConnectionState.done){
if(!snapshot.hasError){
print(snapshot.data.latitude);
返回堆栈(子代:< Widget> [
GoogleMap(
initialCameraPosition:CameraPosition(
目标:LatLng(
snapshot.data.latitude,snapshot.data.longitude),
变焦: 12.0),
onMapCreated:mapCreated,
),
Positioned(
顶部:30.0,
左:15.0,
右:15.0,
孩子:容器(
高度:50.0,
宽度:double.infinity,
装饰:BoxDecoration(
borderRadius:BorderRadius.circular(10.0),
颜色: Colors.white),
子元素:TextField(
装饰:InputDecoration(
边框:InputBorder.none,
hintText:输入地址,
contentPadding:
EdgeInsets.only(顶部:15.0,左侧:15.0),
后缀图标:IconButton(
图标:Icon(Icons.search),
onPressed:searchAndNavigate,
iconSize:30.0,
)),
onChanged:(value){
searchAddress = value;
},
),
),
),
]);
}
} else {
return Center(child:CircularProgressIndicator());
}
}));
}

Future< Position> getCurrentLocation()异步
{
var answer = await Geolocator()。getCurrentPosition();
返回答案;
}


I'm using geolocator plugin and getting current latitude and longitude but i can't load that in initstate of my Flutter Application. It showing Render Error.

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

}

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

}

Map is Got updated with current location after some milli seconds but it showing these errors. I/flutter (14143): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════

I/flutter (14143): The following assertion was thrown building HomePage(dirty, state: _HomePageState#d55de):

I/flutter (14143): 'package:google_maps_flutter/src/location.dart': Failed assertion: line 17 pos 16: 'latitude !=

I/flutter (14143): null': is not true.

I/flutter (14143):

I/flutter (14143): Either the assertion indicates an error in the framework itself, or we should provide substantially

I/flutter (14143): more information in this error message to help you determine and fix the underlying cause.

I/flutter (14143): In either case, please report this assertion by filing a bug on GitHub:

解决方案

As Abbas.M suggestion i'm solving my problem using FutureBuilder Widget.

FutureBuilder Widget: https://www.youtube.com/watch?v=ek8ZPdWj4Qo

I'm declaring variable _future

Future<Position> _future;

I'm calling my async method in the initState

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

Using FutureBuilder widget i solved my problem and i'm passing my async function return value to parameter of FutureBuilder widget.

This Condition if(snapshot.connectionState == ConnectionState.done) helps to find our async function completed and returned value or not. if it is in Done state then it means function completed and returned.

If that condition is not satisfied then it means async function is not completed so i'm using CircularProgressIndicator widget to notify user to understand app is loading.

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;
}

这篇关于无法在Flutter应用程序中加载当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆