【问题标题】:Flutter: async, await [duplicate]颤振:异步,等待[重复]
【发布时间】:2021-03-28 17:24:24
【问题描述】:
void getLocation() async {
  await location.getCurrentLocation();
  *latlng* = LatLng(location.latitude, location.longitude);}

。 .

 @override
 Widget build(BuildContext context) {
  return Scaffold(
   body: Stack(
     children: [
       GoogleMap(
         onMapCreated: _onMapCreated,
         mapType: MapType.normal,
         initialCameraPosition: CameraPosition(
           target: *latlng*,
           zoom: 14.4746,
         ),
       ),

我想在小部件中使用 latlng。但是,'target == null' 是异步输出的。我该怎么办?

【问题讨论】:

  • 欢迎来到 Stackoverflow。如果您没有得到答案,这通常是因为您没有以非常清晰和详细的方式提问。请添加更多信息,然后您将产生更好的影响。
  • 使用 if else,检查 latlng 是否为空,然后显示加载器,直到 latlng 接收到 latlng 后将其传递给 map

标签: flutter asynchronous dart async-await future


【解决方案1】:

通常我们所做的是声明一个布尔值,例如coordAvbl = flase;

在运行获取位置的异步函数时,您使用setState 将布尔值从false 更改为true,这将重建整个小部件树

对于这项工作,您需要在 Scaffold() 中使用三元运算符

这就是你的方式

void getLocation() async {
  await location.getCurrentLocation();
  *latlng* = LatLng(location.latitude, location.longitude);
   setState(() {
      coordAvbl = true;
     
    });
}

并将您的脚手架修改为

override
 Widget build(BuildContext context) {
  return Scaffold(
   body: Stack(
     children: [
       coordAvbl ? GoogleMap(
         onMapCreated: _onMapCreated,
         mapType: MapType.normal,
         initialCameraPosition: CameraPosition(
           target: *latlng*,
           zoom: 14.4746,
         ),
       ) : Container(),
    ]

我猜你错过了一些括号,但是如果coordAvbl = true 那么它会显示我猜的地图,否则它将显示一个空容器。

如有任何错误,欢迎评论

问候, 肉山

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2020-02-16
    • 2019-05-07
    • 2022-01-22
    • 2022-06-19
    • 2019-08-31
    • 2021-05-05
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多