Flutter集成Google Maps后AppBar的Origin/DEST按钮不显示问题求助
问题原因
你代码中AppBar的actions列表里的两个文本按钮都配置了渲染前置条件:
- ORIGIN按钮仅在
_originMarker变量不为空时渲染 - DEST按钮仅在
_destinationMarker变量不为空时渲染
你当前的代码只声明了这两个Marker变量,没有做初始赋值,也没有给出点位选择触发赋值的逻辑,应用启动时两个变量默认值都是null,因此按钮不会被渲染。
解决方法
- 方案1:默认显示按钮,点击时做非空校验
把两个按钮外层的if (_origin != null)和if (_destination != null)判断去掉,按钮点击回调里加非空判断即可,示例代码:
actions: [ TextButton( onPressed: _origin == null ? null : () => _googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: _origin.position, zoom: 14.5, tilt: 50.0, ), ), ), child: Text( 'ORIGIN', style: TextStyle( fontWeight: FontWeight.w600, color: _origin == null ? Colors.grey : Colors.green, ), ), ), TextButton( onPressed: _destination == null ? null : () => _googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: _destination.position, zoom: 14.5, tilt: 50.0, ), ), ), child: Text( 'DEST', style: TextStyle( fontWeight: FontWeight.w600, color: _destination == null ? Colors.grey : Colors.blue, ), ), ), ],
- 方案2:给Marker变量设置初始值
直接在声明时就给_origin和_destination赋值初始点位,启动时按钮就会显示:
Marker _origin = Marker(markerId: const MarkerId('origin'), position: const LatLng(37.773972, -122.431297)); Marker _destination = Marker(markerId: const MarkerId('destination'), position: const LatLng(37.784972, -122.401297));
- 方案3:补充点位选择逻辑
给GoogleMap组件加onTap/onLongPress回调,用户点击/长按地图时给_origin、_destination赋值,调用setState更新UI后按钮就会自动显示。
内容的提问来源于stack exchange,提问作者Usama Bin Tahir
相关产品推荐
相关产品推荐

