Flutter 中的 Google Maps 相机位置更新问题

Posted

技术标签:

【中文标题】Flutter 中的 Google Maps 相机位置更新问题【英文标题】:Google Maps camera position updating issues in Flutter 【发布时间】:2020-10-24 14:33:50 【问题描述】:

我正在使用 Flutter 构建一个基于地图的应用程序。所以我使用谷歌地图包,一切正常。但是,我尝试添加一个 FloatingActionButton 来重新定位我所在位置的地图,在这里,我遇到了问题。首先,地图没有重新定位到我的位置,其次,我收到了一个可怕的红色错误。下面是代码、颤振医生和错误代码。

我的代码:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:spotycar/providers/location_service.dart';

import '../../models/user_location.dart';

class MapWidget extends StatefulWidget 
  MapWidget(@required Key key) : super(key: key);

  @override
  _MapWidgetState createState() => _MapWidgetState();


var locationClicked = false;

class _MapWidgetState extends State<MapWidget> 
  @override
  Widget build(BuildContext context) 
    CameraUpdate cameraUpdate;
    GoogleMapController mapController;
    var location = Provider.of<UserLocation>(context);
    final provider = Provider.of<LocationService>(context);
    final double _zoom = 17.0;
    final double _tilt = 37.0;
    var _coord;

    if (provider.loadedLocation) 
      _coord = LatLng(location.latitude, location.longitude);
      cameraUpdate = CameraUpdate.newCameraPosition(CameraPosition(
        target: _coord,
        bearing: location.heading,
        zoom: _zoom,
        tilt: _tilt,
      ));
    

    if (locationClicked == true) 
      mapController.moveCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            target: _coord,
            bearing: location.heading,
            zoom: _zoom,
            tilt: _tilt,
          ),
        ),
      );
      setState(() 
        locationClicked = false;
      );
    

    return Scaffold(
      body: !provider.loadedLocation
          ? Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.purple),
              ),
            )
          : GoogleMap(
              onMapCreated: (GoogleMapController controller) 
                mapController = controller;
                mapController.animateCamera(cameraUpdate);
              ,
              myLocationEnabled: true,
              myLocationButtonEnabled: false,
              zoomControlsEnabled: false,
              initialCameraPosition: CameraPosition(
                target: _coord,
                zoom: _zoom,
                tilt: _tilt,
              ),
              rotateGesturesEnabled: true,
            ),
    );
  


class LocationRechercheWidget extends StatefulWidget 
  @override
  _LocationRechercheWidgetState createState() =>
      _LocationRechercheWidgetState();


class _LocationRechercheWidgetState extends State<LocationRechercheWidget> 
  @override
  Widget build(BuildContext context) 
    return FloatingActionButton(
      child: Icon(
        Icons.location_searching,
        color: Colors.purple,
        size: 25,
      ),
      backgroundColor: Colors.white,
      onPressed: () 
        setState(() 
          locationClicked = true;
        );
      ,
    );
  

我的 Flutter 医生:

[√] Flutter (Channel master, 1.20.0-3.0.pre.124, on Microsoft Windows [version 10.0.18362.900], locale fr-FR)
    • Flutter version 1.20.0-3.0.pre.124 at C:\flutter
    • Framework revision ec3368ae45 (2 days ago), 2020-07-02 01:58:01 -0400
    • Engine revision 65ac8be350
    • Dart version 2.9.0 (build 2.9.0-20.0.dev f8ff12008e)

 
[√] android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\adrie\AppData\Local\Android\sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Android\Android Studio1310\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
    • All Android licenses accepted.

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio1310
    • Flutter plugin version 45.1.1
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[√] VS Code (version 1.46.1)
    • VS Code at C:\Users\adrie\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.12.1

[√] Connected device (1 available)
    • Mi Note 10 (mobile) • 53bd04cc • android-arm64 • Android 10 (API 29)

• No issues found!

当我点击 FloatingActionButton 时出现的错误:

═╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building MapWidget-[#2721f](dirty, dependencies:
[InheritedProvider<UserLocation>, InheritedProvider<LocationService>], state:
_MapWidgetState#50617):
The method 'moveCamera' was called on null.
Receiver: null
Tried calling: moveCamera(Instance of 'CameraUpdate')
The relevant error-causing widget was:
  MapWidget-[#2721f]
  
lib\screen\map_screen.dart:20
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:51:5)
#1      _MapWidgetState.build 
package:spotycar/…/map_screen/map_widget.dart:39
#2      StatefulElement.build 
package:flutter/…/widgets/framework.dart:4663
#3      ComponentElement.performRebuild 
package:flutter/…/widgets/framework.dart:4546
#4      StatefulElement.performRebuild 
package:flutter/…/widgets/framework.dart:4719
#5      Element.rebuild 
package:flutter/…/widgets/framework.dart:4262
#6      BuildOwner.buildScope 
package:flutter/…/widgets/framework.dart:2667
#7      WidgetsBinding.drawFrame 
package:flutter/…/widgets/binding.dart:866
#8      RendererBinding._handlePersistentFrameCallback 
package:flutter/…/rendering/binding.dart:286
#9      SchedulerBinding._invokeFrameCallback 
package:flutter/…/scheduler/binding.dart:1115
#10     SchedulerBinding.handleDrawFrame 
package:flutter/…/scheduler/binding.dart:1054
#11     SchedulerBinding._handleDrawFrame 
package:flutter/…/scheduler/binding.dart:970
#15     _invoke  (dart:ui/hooks.dart:253:10)
#16     _drawFrame  (dart:ui/hooks.dart:211:3)
(elided 3 frames from dart:async)

【问题讨论】:

为这个方法添加一些代码 'moveCamera' 在 null 上被调用。 @griffins 对不起,我不明白你的回答。 'moveCamera' 方法不是我的,但它是包中的一种方法。我在“onMapCreated”方法中添加了“cameraUpdate”的打印,它返回“'CameraUpdate' 的实例”,但它确实有效。十天后,我仍然有同样的问题,所以欢迎你的帮助! :) 你有什么依赖?我正在尝试运行您的代码来复制问题 谢谢,但我在 GitHub 上找到了解决方案:github.com/flutter/flutter/issues/61451 你在评论中提到你已经解决了这个问题。您能否分享一些见解,让社区了解解决方案是什么?您可以将其放在答案部分并接受为答案。 【参考方案1】:

要解决此问题,您需要使用 Completer 而不是简单的 GoogleMapController。

当你实例化它时:

Completer<GoogleMapController> _controller = Completer();

然后在您的 GoogleMap 小部件内的 onMapCreated 方法中:

onMapCreated: (GoogleMapController controller) 
      _controller.complete(controller);
      ...
,

无论何时你想改变相机位置:

Future<void> moveCamera() async 
  final GoogleMapController controller = await _controller.future;
  controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
    target: LatLong(..., ...),
    zoom: ...,
  )));

你应该很好!

【讨论】:

当前版本不再需要完成器。您可以直接使用控制器。我正在使用google_maps_flutter: ^2.1.1

以上是关于Flutter 中的 Google Maps 相机位置更新问题的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio 中的 Google Maps Flutter 出错

Flutter Google Maps 插件中的原生动画不起作用

Google Maps iOS:移动相机以显示集群内的所有标记

Flutter Google Maps 不会横向滚动

自 pod 更新以来,iOS 地图左上角的 Google Maps 相机目标

google_maps_flutter 与 flutter_facebook_login 不兼容