如何使用geocode在Flutter中显示谷歌Map中心的当前地址?

xurqigkl  于 2023-03-19  发布在  Flutter
关注(0)|答案(1)|浏览(207)

我试图在屏幕上项目的谷歌Map中心的地址在Flutter的帮助下,但我有问题处理期货。这里是我的代码:

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显示纬度和经度时,一切都很好,运行得很好。

e0bqpujr

e0bqpujr1#

FutureBuilder中,您需要在构建GoogleMap之前检查future的状态(是否已完成)。目前,大多数情况下,您尝试在future完成之前构建**。
此外,建议将将来的函数存储在成员中,而不要在生成方法中直接调用它,这样就不会多次调用它。
请尝试以下操作:

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
          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());
        }
      });
  }

相关问题