Flutter中如何使用geocode显示当前google地图中心地址?

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

我正在尝试在 GeoCode 的帮助下在屏幕上投影 Flutter 中谷歌地图中心的地址,但我在处理 Futures 时遇到了问题。这是我的代码:

  class _ManageLocationPage extends State<ManageLocationPage> {
  final List<Marker> _markers = [];
  late GeoPoint chosenLocation;

  late final Future<Address> _getAddressFuture;

  Future<Address> getAddress(GeoPoint currentLocation) async {
    GeoCode geoCode = GeoCode();

    return await geoCode.reverseGeocoding(latitude: currentLocation.latitude, longitude: currentLocation.longitude);
  }

  @override
  void initState(){
    super.initState();
    chosenLocation = widget.startSpot;
    _getAddressFuture = getAddress(chosenLocation);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getAddressFuture,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // future is completed with data, you can build
            Address addr = snapshot.data as Address;
            return Stack(
              alignment: Alignment.center,
              children: [
                GoogleMap(
                    initialCameraPosition: CameraPosition(
                        target: LatLng(
                            widget.startSpot.latitude, widget.startSpot.longitude),
                        zoom: 18),
                    zoomControlsEnabled: false,
                    compassEnabled: false,
                    indoorViewEnabled: true,
                    mapToolbarEnabled: false,
                    onMapCreated: (controller) {
                      final marker = Marker(
                        markerId: MarkerId('0'),
                        position: LatLng(
                            widget.startSpot.latitude, widget.startSpot.longitude),
                      );
                      _markers.add(marker);
                    },
                    onCameraMove: (position) {
                      chosenLocation = GeoPoint(position.target.latitude, position.target.longitude);
                      setState(() {
                        _markers.first =
                            _markers.first.copyWith(positionParam: position.target);
                      });
                    },

                ),
                Positioned(
                  top: Dimensions.height45 + Dimensions.height10,
                  left: Dimensions.width20,
                  right: Dimensions.width20,
                  child: Container(
                      padding: EdgeInsets.symmetric(horizontal: Dimensions.width10),
                      height: 50,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(Dimensions.radius20/2),
                          boxShadow: [
                            BoxShadow(
                                blurRadius: 10,
                                spreadRadius: 7,
                                offset: Offset(1, 10),
                                color: Colors.grey.withOpacity(0.2)
                            )
                          ]
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.storefront, size: 25, color: AppColors.iconColor1),
                          SizedBox(width: Dimensions.width10,),
                          Expanded(child: SmallText(text: addr.streetAddress.toString(),)),
                        ],
                      )
                  ),
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(bottom: 42),
                      child: Icon(
                        Icons.location_on,
                        color: AppColors.mainColor,
                        size: 50,
                      ),
                    ),
                  ],
                ),
              ],
            );
          } else if (snapshot.hasError) {
            // handler errors
            return const Text('Error');
          }
          else {
            // future is not completed yet, display a progress indicator
            return const Center(child: CircularProgressIndicator());
          }
        });
  }
}

当我尝试运行时,出现错误

type Future<Address> is not a subtype of type Address
。 当我不使用地理编码而只是通过打印
chosenLocation
显示纬度和经度时,一切都很好并且进展顺利。

flutter dart google-maps future geocode
1个回答
0
投票

FutureBuilder
中,您需要在构建
GoogleMap
之前检查未来的状态(是否已完成)。目前,大多数时候你会在未来完成之前尝试构建

另外,建议将future函数存放在成员中,不要直接在build方法中调用,以免被多次调用

尝试以下操作:

class _ManageLocationPage extends State<ManageLocationPage> {
  final List<Marker> _markers = [];
  late GeoPoint chosenLocation;
  
  late final Future<Address> _getAddressFuture;
  

  getAddress(GeoPoint currentLocation) async {
    GeoCode geoCode = GeoCode();

    return await geoCode.reverseGeocoding(latitude: 
      currentLocation.latitude, 
      longitude: currentLocation.longitude);
  }


  @override
  void initState(){
    super.initState();
    chosenLocation = widget.startSpot;
    _getAddressFuture = getAddress(chosenLocation);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _getAddressFuture,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          // future is completed with data, you can build
          return Stack(...);
        } else if (snapshot.hasError) {
          // handler errors
          return const Text('Error');
        }
        else {
          // future is not completed yet, display a progress indicator
          return const Center(child: CircularProgressIndicator());
        }
      });
  }

© www.soinside.com 2019 - 2024. All rights reserved.