Flutter 颤振:点击两次按钮后,仅文本更新
我刚开始在Flatter中构建一个天气应用程序,我遇到了一个问题,即获取并显示用户的位置作为文本小部件需要点击两次按钮。我想让用户只需点击一次location FlatButton,文本就可以用当前位置更新。这是我的代码(我删去了不必要的部分+样板代码):Flutter 颤振:点击两次按钮后,仅文本更新,flutter,dart,geolocation,location,Flutter,Dart,Geolocation,Location,我刚开始在Flatter中构建一个天气应用程序,我遇到了一个问题,即获取并显示用户的位置作为文本小部件需要点击两次按钮。我想让用户只需点击一次location FlatButton,文本就可以用当前位置更新。这是我的代码(我删去了不必要的部分+样板代码): class\u状态扩展状态{ 位置; 列出地名; 字符串位置; void getLocation()异步{ 位置=等待地理定位器() .getCurrentPosition(所需精度:定位精度最低); placemark=等待地理定位器()
class\u状态扩展状态{
位置;
列出地名;
字符串位置;
void getLocation()异步{
位置=等待地理定位器()
.getCurrentPosition(所需精度:定位精度最低);
placemark=等待地理定位器()
.placemarkFromCoordinates(位置、纬度、位置、经度);
地点=地名[0]。地点+“,”+地名[0]。国家;
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:安全区(
孩子:填充(
填充:常数边集全部(25.0),
子:列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
//我暂时不考虑其他孩子
//这是我希望用户点击位置图标后显示其位置的地方
正文(
placemark!=null?位置:“点击位置图标…”,
样式:TextStyle(
颜色:颜色,白色,
尺寸:20,
fontWeight:fontWeight.w800,
),
//这是位置图标
填充物(
填充:仅限常量边集(顶部:100.0),
孩子:扁平按钮(
子:图标(
Icons.my_位置,
颜色:颜色,白色,
),
颜色:颜色。透明,
已按下:(){
设置状态(){
getLocation();
});
},
),
),
),
],
),
),
),
),
);
}
}
我想我解决了您的问题,方法是按您现在的方式调用set state,而不是在重建之前等待地理定位器
数据返回。这就是为什么需要单击两下才能显示数据的原因。尝试此设置
Future<void> getLocation() async {
position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.lowest);
placemark = await Geolocator()
.placemarkFromCoordinates(position.latitude, position.longitude);
location = placemark[0].locality + ", " + placemark[0].country;
setState(() {});
}
//then the onPressed function in your padding widget should be
onPressed: () async {
await getLocation();
},
Future getLocation()异步{
位置=等待地理定位器()
.getCurrentPosition(所需精度:定位精度最低);
placemark=等待地理定位器()
.placemarkFromCoordinates(位置、纬度、位置、经度);
地点=地名[0]。地点+“,”+地名[0]。国家;
setState((){});
}
//然后,padding小部件中的onPressed函数应该是
onPressed:()异步{
等待getLocation();
},
Future<void> getLocation() async {
position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.lowest);
placemark = await Geolocator()
.placemarkFromCoordinates(position.latitude, position.longitude);
location = placemark[0].locality + ", " + placemark[0].country;
setState(() {});
}
//then the onPressed function in your padding widget should be
onPressed: () async {
await getLocation();
},