title: Flutter Maps: onTap with dynamically added markers - showModalBottomSheet returns error
body: <p>I'm using flutter to take data from a Realtime Database and add a marker on a Google Map for each element. When the user clicks on one of these markers, I would like to pop up a bottom sheet with more information. When I try to do this with the below code, however, I get the following runtime error:</p>
  <pre><code>
  E/flutter (25294): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: No MediaQuery widget ancestor found.
  E/flutter (25294): MyApp widgets require a MediaQuery widget ancestor.
  E/flutter (25294): The specific widget that could not find a MediaQuery ancestor was:
  E/flutter (25294):   MyApp
  E/flutter (25294): The ownership chain for the affected widget is: &quot;MyApp ← [root]&quot;
  E/flutter (25294): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
  </code></pre>
  <p>I have tried to use _myContext (which I set in the build method), but the error remains the same.</p>
  <p>This is my main.dart:</p>
  <pre><code>import 'package:flutter/material.dart';
  import 'package:google_maps_flutter/google_maps_flutter.dart';
  import 'package:firebase_core/firebase_core.dart';
  import 'package:firebase_database/firebase_database.dart';
  import 'dart:convert';
  
  import 'package:petrol_finder/data/PetrolStation.dart';
  
  void main() {
    WidgetsFlutterBinding.ensureInitialized();
    runApp(MyApp());
  }
  class MyApp extends StatefulWidget {
    const MyApp({Key? key}) : super(key: key);
  
    @override
    _MyAppState createState() =&gt; _MyAppState();
  }
  
  class _MyAppState extends State&lt;MyApp&gt; {
    BuildContext? _myContext;
    late GoogleMapController mapController;
    final petrolStationsDatabase = FirebaseDatabase(databaseURL:&quot;[removed].firebasedatabase.app/&quot;).reference().child('petrolstations');
    final Set&lt;Marker&gt; markers = Set();
  
    bool _initialized = false;
    bool _error = false;
    bool _showModalBottomSheet = false;
  
    final LatLng _center = const LatLng(51.5074, -0.1272);
  
  
    void _onMapCreated(GoogleMapController controller) {
      mapController = controller;
    }
  
  // Define an async function to initialize FlutterFire
    void initializeFlutterFire() async {
      try {
        // Wait for Firebase to initialize and set `_initialized` state to true
        await Firebase.initializeApp();
        setState(() {
          _initialized = true;
        });
      } catch(e) {
        // Set `_error` state to true if Firebase initialization fails
        setState(() {
          _error = true;
        });
      }
    }
    @override
    void initState() {
      initializeFlutterFire();
      super.initState();
      _activateListeners();
    }
    void _activateListeners()
    {
      petrolStationsDatabase.onChildAdded.listen((event)
      {
        if(event.snapshot.key==null) {
          return;
        }
  
        final PetrolStation petrolStation = PetrolStation.fromJson(event.snapshot.value);
        debugPrint(event.snapshot.key);
        debugPrint(petrolStation.address);
        debugPrint(petrolStation.latitude.toString());
  
        markers.add(Marker(
          markerId: MarkerId(event.snapshot.key==null?&quot;ERROR&quot;:event.snapshot.key!),
          position: LatLng(petrolStation.latitude, petrolStation.longitude),
          onTap: () {
            debugPrint(&quot;TAP&quot;);
  
            showModalBottomSheet&lt;void&gt;(
              context: _myContext!,
              builder: (context) {
                return Container(
                  height: 200,
                  color: Colors.amber,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.min,
                      children: &lt;Widget&gt;[
                        const Text('Modal BottomSheet'),
                        ElevatedButton(
                          child: const Text('Close BottomSheet'),
                          onPressed: () =&gt; Navigator.pop(context),
                        )
                      ],
                    ),
                  ),
                );
              }, // builder
            ); //showmodalbottomsheet
  
          },
            icon:BitmapDescriptor.defaultMarker,
        ));
        //petrolStations.add(petrolStation);
        //debugPrint(petrolStations.length.toString());
      });
    }
  
    Widget SomethingWentWrong()
    {
      return ErrorWidget(&quot;An error has occurred in initialising Firebase&quot;);
    }
    Widget Loading()
    {
      return SizedBox.shrink();
    }
  
    @override
    Widget build(BuildContext context) {
      _myContext = this.context;
      // Show error message if initialization failed
      if(_error) {
        return SomethingWentWrong();
      }
      // Show a loader until FlutterFire is initialized
      if (!_initialized) {
        return Loading();
      }
  
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Petrol Finder'),
            backgroundColor: Colors.green[700],
          ),
          body: GoogleMap(
            onMapCreated: _onMapCreated,
            initialCameraPosition: CameraPosition(
              target: _center,
              zoom: 11.0,
            ),
            markers: this.markers,
          ),
        ),
      );
    }
  }
  </code></pre>