在Dart / Flutter中实现异步/等待

时间:2020-10-02 08:56:39

标签: flutter dart async-await

  1. 为什么构建方法在重新启动时显示“ NULL”,但是在热重载时更新纬度值?

  2. 是否可以将Text('Lat:$ latitude')加载为initState()本身?

class _LoadingScreenState extends State<LoadingScreen> {
  double latitude;
  double longitude;

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  void getLocation() async {
    Location location = Location();

    await location.getCurrentLocation();

    latitude = location.latitude;
    longitude = location.longitude;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(child: Text('Lat: $latitude')),
    );
  }
}

3 个答案:

答案 0 :(得分:0)

那是因为在更改数据时您没有调用setState方法,因此该小部件不会重新构建自身。

应该是这样的:

void getLocation() async {
    Location location = Location();

    await location.getCurrentLocation();

    setState(() {
      latitude = location.latitude;
      longitude = location.longitude;
    });
  }

答案 1 :(得分:0)

latitude在构建方法构造窗口小部件时没有时间分配值。

使用setState方法包装纬度和经度,以通知框架应该进行新的构建。这样,纬度值将在可用时立即更新。

setState(() {
 latitude = location.latitude;
 longitude = location.longitude;
});

一个技巧是在等待分配值时显示其他内容而不是latitude值。例如成为CircularProgressIndicator。

答案 2 :(得分:0)

与上面的答案一样,getLocation是异步的,表示它将在将来完成,在重新启动时,您将获得当前的纬度,该纬度为null,因为尚未获得该值,因此在热重载时您将显示该值那已经完成了 您可以在上面的有状态类中使用setState, 或者您可以使用futurebuilder在可用时显示该值。