颤振:仅在两次点击按钮后更新文本

时间:2020-04-14 22:44:47

标签: flutter dart geolocation location

我刚刚开始在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();
                      });
                    },
                  ),
                ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

我认为我是通过以下方式解决您的问题的:通过调用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();
               },