首页 > 解决方案 > Flutter google_maps_flutter 无法通过 PopupMenuButton 更改 MapType

问题描述

我只是在玩新的 Flutter谷歌地图包。

我想MapType通过使用PopupMenuButton. 下面是我的代码。

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapPage extends StatefulWidget {
  @override
  _MapPageState createState() => _MapPageState();
}

class _MapPageState extends State<MapPage> {
  GoogleMapController mapController;
  List arrMapTyep = [
    {'title': 'none', 'value': MapType.none},
    {'title': 'hybrid', 'value': MapType.hybrid},
    {'title': 'normal', 'value': MapType.normal},
    {'title': 'satellite', 'value': MapType.satellite},
    {'title': 'terrain', 'value': MapType.terrain}
  ];
  MapType currentMapType = MapType.normal;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Map"),
        actions: <Widget>[
          PopupMenuButton(
              icon: Icon(Icons.more_vert),
              initialValue: currentMapType,
              onSelected: (value) {
                setState(() {
                  currentMapType = value;
                });
              },
              itemBuilder: (BuildContext context) => _setupAllMapType()
              )
        ],
      ),
      body: Container(
        child: GoogleMap(
          onMapCreated: _onMapCreated,
          options: GoogleMapOptions(
              mapType: currentMapType,
              compassEnabled: true,
              myLocationEnabled: true,
              cameraPosition: CameraPosition(
                  target: LatLng(37.785834, -122.406417), 
                  zoom: 16,
                )
              ),
        ),
      ),
    );
  }

  void _onMapCreated(GoogleMapController controller) {
    setState(() {
      mapController = controller;
    });
  }

  List<PopupMenuItem> _setupAllMapType() {
    List<PopupMenuItem> temArr = List();
    for (var i = 0; i < arrMapTyep.length; i++) {
      temArr.add(
        PopupMenuItem(
          value: arrMapTyep[i]['value'],
          child: Text(arrMapTyep[i]['title']),
        ),
      );
    }

    return temArr;
  }
}

我打电话setState但可以工作。

标签: google-mapsdartflutter

解决方案


我不确定现在回答这个问题是否为时已晚,但万一像我这样的人偶然发现了这个问题;

MapType 的实时更改,可以使用 setState() 调用 currentMapType 变量来实现。我已经在我的应用程序中实现了这一点,它像黄油一样顺畅!

希望能帮助到你。快乐飘飘!

快速参考(将法线贴图类型更改为卫星贴图类型):

   RaisedButton(
     child: Text("Satellite"),
     onPressed: () {
        setState(() {
           currentMapType = MapType.satellite;
        });
     },
   )

推荐阅读