【问题标题】:Flutter correct way to handle Future in multiple classes (Google Maps)Flutter 在多个类中处理 Future 的正确方法(谷歌地图)
【发布时间】:2019-12-19 13:16:51
【问题描述】:

我有一个模型类

LocalInfo.dart

class LocationInfo {
  // LocationController
  Location location = Location();

  //Location Position Data
  LocationData currentLocation;
  double longitude;
  double latitude;

  LocationInfo() {
    try {
      location.getLocation().then((location) {
        currentLocation = location;
        longitude = currentLocation.longitude;
        latitude = currentLocation.latitude;
      });
    } catch (e) {
      currentLocation = null;
    }
  }
}

还有我的地图类 MapsService.dart

MapsService() {
    loading = true;
    locationInfo = LocationInfo(); // <== This takes some time
    cameraPosition = CameraPosition(
        zoom: 15,
        target: LatLng(locationInfo.latitude, locationInfo.longitude)); // <-- Latitude Longitude is null
    loading = false;
  }

这里的问题是我创建了一个具有经度和纬度作为类成员的 LocationInfo 模型对象。但是由于 location.getLocation() 返回的是 Future,因此需要一些时间来获取这些值。

但是在我的 MapsService 类中,我创建了一个 LocationInfo 对象并将 cameraPosition 设置为给定的纬度和经度。但是我怎么能等待经度和纬度值呢? Long/Lat 为 null 并导致应用程序崩溃,因为我不等待。

我需要在我的 MapService 构造函数中等待 LocationInfo。它必须在我设置 Lat 和 Long 值之前完成

【问题讨论】:

    标签: flutter dart future


    【解决方案1】:

    您不能只在模型中使用外部 API。 ModelClass 只是一个数据。您只需在应用程序的某个位置启动订阅,并更新与您的地图小部件相关的数据

    理想情况下,您需要这样的东西:

    LocationInfo userPosition;
    StreamSubscription<LocationData> positionSubscription;
    
    @override
    void initState() {
      super.initState();
      positionSubscription = location
          .onLocationChanged()
          .handleError((error) => print(error))
          .listen(
            (newPosition) => setState(() {
              _currentLocation = LocationInfo(
                latitude: newPosition.latitude,
                longitude: newPosition.longitude,
              );
            }),
          );
    }
    
    @override
    void dispose() {
      positionSubscription?.cancel();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return MapWidget(userPosition);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-06
      • 2020-05-12
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      相关资源
      最近更新 更多