首页 > 解决方案 > 如何在 Flutter 中设置 Google Map 主题?

问题描述

我有一个地图应用程序,我想在日出和日落时更改主题。为地图设置主题应该非常简单,但我收到以下错误。

未处理的异常:NoSuchMethodError:在 null 上调用了方法“setMapStyle”。

这是我的 pubspec.yaml

assets:
  - assets/themes/map/day/
  - assets/themes/map/night/

我已经导入了以下包。

import 'package:flutter/services.dart' show rootBundle;

我在我的 initState() 中添加了以下行

rootBundle.loadString('assets/themes/map/night/night.json').then((string) {
      _mapStyle = string;
    });

这是我的地图控制器。

Completer<GoogleMapController> _mapController = Completer();

void _onMapCreated(GoogleMapController controller) {
    PermissionHandler()
        .checkPermissionStatus(PermissionGroup
            .locationWhenInUse) //check permission returns a Future
        .then(_updateStatus); // handling in callback to prevent blocking UI

    _mapController.complete(
     controller); // manages camera function (position, animation, zoom).

    controller.setMapStyle(_mapStyle);
    print("MAPSTYLE -> $_mapStyle");
  }

这是我的地图代码的开始

_userLocation == null
    ? Center(
        child: CircularProgressIndicator(
            backgroundColor: Theme.UniColour.primary[900],
        ))
        : GoogleMap(
            onMapCreated: _onMapCreated,
            initialCameraPosition:
                CameraPosition(
                    target: _userLocation,
                    zoom: _defaultZoom,
                    tilt: _tiltAngle),
                    ...
                    ...
                    ...

任何帮助将不胜感激。

标签: google-mapsflutterdartthemes

解决方案


这段代码对我有用。

controller.setMapStyle(await rootBundle.loadString('assets/styles/google_map.json'));

使用异步等待来防止竞争条件。


推荐阅读