google-maps - 在 initState() 中调用时, flutter 的谷歌地图自定义图标不显示

标签 google-maps flutter dart

我在我的 flutter 应用程序中使用 google_maps_flutter 1.0.2 创建了一个 map View ,并且我在我的 map View 上设置了 3 个不同的自定义标记。其中两个是使用复选框设置的,但我想在应用程序首次启动时显示第一组自定义标记。使用此代码,我可以在首次启动应用程序时设置标记,但标记图标是默认的(红色气球状图标)而不是我的自定义图标,但如果我点击复选框两次,我将使用我的图标获得标记。我什至尝试使用 after_layout 库修复此问题,但没有运气。

import 'dart:async';
import 'package:expandable_bottom_sheet/expandable_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:location/location.dart';
import 'package:after_layout/after_layout.dart';

class RoadAssistance extends StatefulWidget {
  @override
  _RoadAssistanceState createState() => _RoadAssistanceState();
}

class _RoadAssistanceState extends State<RoadAssistance>
    with AfterLayoutMixin<RoadAssistance> {
  Completer<GoogleMapController> _controller = Completer();
  CameraPosition _currentPosition = CameraPosition(
    target: LatLng(6.9147, 79.9729),
    zoom: 15.4746,
  );
  Set<Marker> markers = Set();
  Set<Marker> markers1 = Set();

  bool askingPermission = false;
  bool showGarages = false;
  bool showBranches = true;
  bool firstTime = true;

  LocationData _locationData;
  BitmapDescriptor myPosIcon;
  BitmapDescriptor branchIcon;
  BitmapDescriptor garageIcon;

  @override
  void initState() {
    super.initState();
    BitmapDescriptor.fromAssetImage(
            ImageConfiguration(size: Size(55, 55)), 'images/me.png')
        .then((onValue) {
      myPosIcon = onValue;
    });

    BitmapDescriptor.fromAssetImage(
            ImageConfiguration(size: Size(55, 55)), 'images/home-city.png')
        .then((onValue) {
      branchIcon = onValue;
    });

    BitmapDescriptor.fromAssetImage(
            ImageConfiguration(size: Size(48, 48)), 'images/wrench.png')
        .then((onValue) {
      garageIcon = onValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    var padding = MediaQuery.of(context).padding;

    return Scaffold(
        appBar: AppBar(
          title: Text('Road Assitance'),
          backgroundColor: Color.fromRGBO(0, 172, 192, 100),
        ),
        body: ExpandableBottomSheet(
          background: Stack(children: [
            SizedBox(
              height: height - 130,
              child: GoogleMap(
                mapType: MapType.normal,
                initialCameraPosition: _currentPosition,
                myLocationEnabled: true,
                myLocationButtonEnabled: true,
                markers: markers,
                onMapCreated: (GoogleMapController controller) {
                  _controller.complete(controller);
                },
              ),
            ),
            Container(
              padding: EdgeInsets.all(5),
              width: width,
              height: height - 240,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black38.withOpacity(0.6),
                              spreadRadius: 1,
                              blurRadius: 4,
                              offset:
                                  Offset(0, 3), // changes position of shadow
                            ),
                          ],
                        ),
                        width: 160,
                        padding: EdgeInsets.all(5),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: 30.0,
                              width: 30.0,
                              child: Checkbox(
                                  value: showBranches,
                                  onChanged: (bool newValue) {
                                    newValue
                                        ? loadBranches()
                                        : unloadBranches();
                                    setState(() {
                                      showBranches = newValue;
                                      print(newValue);
                                    });
                                  }),
                            ),
                            Icon(
                              MdiIcons.homeCity,
                              color: Colors.green[700],
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            Text(
                              'Branches',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black38.withOpacity(0.6),
                              spreadRadius: 1,
                              blurRadius: 4,
                              offset:
                                  Offset(0, 3), // changes position of shadow
                            ),
                          ],
                        ),
                        width: 160,
                        padding: EdgeInsets.all(5),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: 30.0,
                              width: 30.0,
                              child: Checkbox(
                                  value: showGarages,
                                  onChanged: (bool newValue) {
                                    newValue ? loadGarages() : unloadGarages();
                                    setState(() {
                                      showGarages = newValue;
                                      print(newValue);
                                    });
                                  }),
                            ),
                            Icon(
                              MdiIcons.hammerWrench,
                              color: Colors.orange[700],
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            Text(
                              'Garages',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                  
                ],
              ),
            ),
          ]), 
        ),
  }

  @override
  void afterFirstLayout(BuildContext context) {
    // Calling the same function "after layout" to resolve the issue.
    loadBranches();
    print("function called");
  }

  getLocation() async {
    Location location = new Location();
    LocationData _locationData1;
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;

    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
    _locationData1 = await location.getLocation();

    print(_locationData1);
    final GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(_currentPosition));
    markers.add(
      Marker(
        markerId: MarkerId('I\'m Here'),
        position: LatLng(_locationData1.latitude, _locationData1.longitude),
        icon: myPosIcon,
      ),
    );
    setState(() {
      _currentPosition = new CameraPosition(
        target: LatLng(_locationData1.latitude, _locationData1.longitude),
        zoom: 15.4746,
      );
    });
  }

  loadGarages() {
    print("laod garages called");
    markers.addAll([
      Marker(
        markerId: MarkerId('SLIC Garage'),
        position: LatLng(6.9217, 79.9739),
        infoWindow: InfoWindow(title: 'SLIC Garage New'),
        icon: garageIcon,
      ),
      Marker(
        markerId: MarkerId('SLIC Garage 2'),
        position: LatLng(6.9197, 79.9639),
        infoWindow: InfoWindow(title: 'SLIC Garage Nugapityiia'),
        icon: garageIcon,
      ),
      Marker(
        markerId: MarkerId('SLIC Garage 3'),
        position: LatLng(6.9087, 79.9729),
        infoWindow: InfoWindow(title: 'SLIC Garage '),
        icon: garageIcon,
      ),
    ]);
  }

  unloadGarages() {
    print("unlaod garages called");
    markers.removeWhere((x) => x.icon == garageIcon);
  }

  loadBranches() {
    print("laod branches called");
    markers.addAll([
      Marker(
        markerId: MarkerId('SLIC Branch'),
        position: LatLng(6.9167, 79.9749),
        infoWindow: InfoWindow(title: 'SLIC Branch Hewagama'),
        icon: branchIcon,
      ),
      Marker(
        markerId: MarkerId('SLIC Branch 2'),
        position: LatLng(6.9157, 79.9639),
        infoWindow: InfoWindow(title: 'SLIC Branch Kotahawala'),
        icon: branchIcon,
      ),
      Marker(
        markerId: MarkerId('SLIC Branch Malabe'),
        position: LatLng(6.9287, 79.9729),
        icon: branchIcon,
      ),
    ]);
  }

  unloadBranches() {
    if (firstTime) {
      markers.clear();
      firstTime = false;
      return;
    }
    print("unlaod branches called");
    markers.removeWhere((x) => x.icon == branchIcon);
  }
}

最佳答案

你可以试试这个:

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
        myPosIcon = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size: Size(55, 55)), 'images/me.png');

        branchIcon = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size: Size(55, 55)), 'images/home-city.png');

        garageIcon = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size: Size(48, 48)), 'images/wrench.png');

        setState(() {});
      });
    super.initState();
  }

关于google-maps - 在 initState() 中调用时, flutter 的谷歌地图自定义图标不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64231440/

相关文章:

dart - 如何在 Dart 中生成一个不包含特定编号的随机数?

android - Google Map V2 android 错误 Inflating class fragment 错误

javascript - 从文本区域在谷歌地图上绘制kml图层

ios - Google map ,使用 DispatchQueue 加载标记

calendar - 如何处理 Flutter 中日历轮播中单击时的按钮颜色

dart - 如何避免在Dart中转义引用?

dart - 如何自定义 TabBar 指示器的宽度和高度?

iphone - 通过 iPhone 连接到 AT&T 无线网络的 Google 静态 map 无法正常工作

flutter 获取带参数的请求

android - 使用简单边缘检测 flutter 时出现运行时错误