Skip to content

[google_maps_flutter_web] Bad state: Cannot add new events after calling close #168782

@JamesMcIntosh

Description

@JamesMcIntosh

PR

flutter/packages#9250

Related issue tickets

#159388
#75818

Steps to reproduce

While the map is animating to the new position dispose the map (i.e. replace it in the widget tree).
Inspect the developer tools console for the error message.

Expected results

No error messages in the console as the disposed widget should no longer be listening to map events.

Actual results

Error messages in the console as events are still trying to be sent from the map to the controller.

Code sample

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

void main() {
  runApp(const MapToggleWidget());
}

class MapToggleWidget extends StatefulWidget {
  const MapToggleWidget({Key? key}) : super(key: key);

  @override
  _MapToggleWidgetState createState() => _MapToggleWidgetState();
}

class _MapToggleWidgetState extends State<MapToggleWidget> {
  bool _showMap = true;
  GoogleMapController? _mapController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Map Toggle Example')),
        body: Column(
          children: [
            Expanded(child: _showMap ? buildGoogleMap() : buildNoMapContainer()),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                onPressed: () => setState(() => _showMap = !_showMap),
                child: Text(_showMap ? 'Hide Map' : 'Show Map'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Container buildNoMapContainer() {
    return Container(
      color: Colors.grey[300],
      child: const Center(
        child: Text(
          'Map is hidden',
          style: TextStyle(fontSize: 18),
        ),
      ),
    );
  }

  GoogleMap buildGoogleMap() {
    return GoogleMap(
      mapType: MapType.satellite,
      initialCameraPosition: const CameraPosition(
        target: LatLng(-38.9000, 175.8000),
        zoom: 10.0,
      ),
      onMapCreated: _onMapCreated,
    );
  }

  void _onMapCreated(GoogleMapController controller) {
    _mapController = controller;
    // wait a moment for layout, then move camera to fit the bounds
    Future.delayed(const Duration(milliseconds: 100), () {
      _mapController?.animateCamera(
        CameraUpdate.newLatLngBounds(
            LatLngBounds(
              southwest: const LatLng(-38.9000, 175.8000),
              northeast: const LatLng(-38.4000, 176.4000),
            ),
            50.0),
        duration: const Duration(seconds: 5),
      );
    });
  }
}

Screenshots or Video

No response

Logs

Logs
errors.dart:307 Uncaught (in promise) DartError: Bad state: Cannot add new events after calling close
    at Object.throw_ [as throw] (errors.dart:307:3)
    at async._AsyncBroadcastStreamController.new.add (broadcast_stream_controller.dart:256:24)
    at google_maps_controller.dart:271:7
    at _RootZone.runUnaryGuarded (zone.dart:1778:9)
    at [_sendData] (stream_impl.dart:381:5)
    at async._DelayedData.new.perform (stream_impl.dart:573:13)
    at async._PendingEvents.new.handleNext (stream_impl.dart:678:10)
    at async._AsyncCallbackEntry.new.callback (stream_impl.dart:649:7)
    at Object._microtaskLoop (schedule_microtask.dart:40:11)
    at _startMicrotaskLoop (schedule_microtask.dart:49:5)
    at async_patch.dart:186:7

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.29.2, on macOS 15.4.1 24E263 darwin-arm64, locale en-AU) [2.1s]
    • Flutter version 3.29.2 on channel stable at /Users/james/fvm/versions/3.29.2
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision c236373904 (9 weeks ago), 2025-03-13 16:17:06 -0400
    • Engine revision 18b71d647a
    • Dart version 3.7.2
    • DevTools version 2.42.3.

[✓] Chrome - develop for the web [31ms]
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.29Found to occur in 3.29found in release: 3.33Found to occur in 3.33has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: mapsGoogle Maps pluginpackageflutter/packages repository. See also p: labels.platform-webWeb applications specificallyr: fixedIssue is closed as already fixed in a newer versionteam-webOwned by Web platform teamtriaged-webTriaged by Web platform team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions