Search code examples
flutterdartgoogle-mapsfloating-action-buttonontap

onTap of GoogleMap triggered when clicking FloatingActionButton (Flutter web)


I'm doing a web application with Flutter using the google_maps_flutter package. I added a GoogleMap to my web app with onTap event which adds marker on the map. I also want to add a floating action button on top of the map but the problem is that whenever the button is clicked (left click using a mouse on a computer), a new marker is added because onTap is triggered. I don't want that. How can I fix it? The only thing I can think of is onLongPress (right click on a computer) but I'd prefer to avoid it if there is another way by keeping onTap.

  void _addLocation(LatLng latLng){
    setState(() {
      _locationsCount++;
      _locations.add(Marker(
        markerId: MarkerId(_locationsCount.toString()),
        position: latLng,
        ));
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Stack(
        children: <Widget>[
          GoogleMap(
            onMapCreated: _onMapCreated,
            initialCameraPosition: CameraPosition(
              target: _center,
              zoom: 8.0,
              ),
            onTap: _addLocation,
            markers: Set<Marker>.of(_locations),
          ),
          Text(
            'Number of locations: $_locationsCount',
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _calculate,
        backgroundColor: Colors.green,
        label: const Text('Calculate'),
        icon: const Icon(Icons.calculate),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }

Solution

  • This is a common problem in Flutter web described in details in this issue : https://github.com/flutter/flutter/issues/72273

    In a nutshell to solve your problem you should add this package to your project : https://pub.dev/packages/pointer_interceptor

    Then wrap FloatingActionButton with the PointerInterceptor widget. The finale code should look like this :

    floatingActionButton: PointerInterceptor(
       child: FloatingActionButton.extended(
          onPressed: _calculate,
          backgroundColor: Colors.green,
          label: const Text('Calculate'),
          icon: const Icon(Icons.calculate),
        ),
     ),