Flutter:仅在轻按两次按钮后才更新文本

问题描述 投票:0回答:1

我刚刚开始在Flutter中构建气象应用程序,但遇到了这样的问题:要获取和显示用户位置为“文本”小部件,需要轻按两次FlatButton。我要这样做,以便用户只需点击一次FlatButton位置,文本就可以使用其当前位置进行更新。这是我的代码(我删除了不必要的部分+样板代码):

class _ClimaState extends State<Clima> {
  Position position;
  List<Placemark> placemark;
  String location;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[

                //I've left out the other children for now

                //This is where I want the user's location to be displayed after they tap the location icon
                Text(
                  placemark != null ? location : "Tap the location icon...",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.w800,

                  ),

                //This is the location icon
                Padding(
                  padding: const EdgeInsets.only(top: 100.0),
                  child: FlatButton(
                    child: Icon(
                      Icons.my_location,
                      color: Colors.white,
                    ),
                    color: Colors.transparent,
                    onPressed: () {
                      setState(() {
                        getLocation();
                      });
                    },
                  ),
                ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
flutter dart geolocation location
1个回答
0
投票

[我想我是通过调用set state来解决您的问题的,而您在重建之前不等待Geolocator数据返回,这就是为什么需要两次单击才能显示数据的原因。尝试此设置

  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();
               },
© www.soinside.com 2019 - 2024. All rights reserved.