Flutter Google Map works on Android version but not on iPhone version

I use the flutter application programming language

I created a page containing Google Maps through which the user specifies his location to save the address and location data in his account when creating the account

When running the version on Android, it works well

But when running the version on iPhone, the map does not appear

I put all the required permissions

And I modified the AppDelegate.swift file and added the api key to the file

However, it did not work

Xcode version 16

IOS 18

dart 3.5.4

flutter 3.22

class MapScreen extends StatefulWidget {
  const MapScreen({super.key});
  @override
  State<MapScreen> createState() => OrderTrackingPageState();
}

class OrderTrackingPageState extends State<MapScreen> {
  double? latitude;
  double? longitude;
  final Completer<GoogleMapController> _controller = Completer();

  LocationData? currentLocation;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    getCurrentLocation();

    if (currentLocation != null) {
      setState(() {
        _isLoading = false;
        sourceLocation =
            LatLng(currentLocation!.latitude!, currentLocation!.longitude!);
        latitude = currentLocation!.latitude;
        longitude = currentLocation!.longitude;
      });
    }
  }

  LatLng? sourceLocation;
  String _selectedAddress = '';
  String City = '';
  String Country = '';
  String Postalcode = '';
  String State = '';
  String Address = '';

  void _handleMapLongPress(LatLng position) async {
    String apiKey = 'AIz***********************************';
    String url =
        'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$apiKey';

    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(response.body);
      if (data['status'] == 'OK') {
        String formattedAddress = data['results'][0]['formatted_address'];
        List<String> addressParts = formattedAddress.split(', ');
        String country = addressParts.last;
        String city = addressParts[addressParts.length - 2];
        String street =
            addressParts.sublist(0, addressParts.length - 2).join(', ');

        setState(() {
          Address = street;
          City = city;
          Country = country;
        });

        List<dynamic> addressComponents =
            data['results'][0]['address_components'];
        String postalCode = '';
        String state = '';

        for (var component in addressComponents) {
          List<dynamic> types = component['types'];
          if (types.contains('postal_code')) {
            postalCode = component['long_name'];
            setState(() {
              Postalcode = postalCode;
            });
          } else if (types.contains('administrative_area_level_1')) {
            state = component['long_name'];
            setState(() {
              State = state;
            });
          }
        }

        setState(() {
          _selectedAddress = '''
$country, $city,
$street
Postal Code: $postalCode
State: $state
''';
        });
      }
    }
  }

  void _showAddressPopup() {
    showDialog(
      context: context,
      builder: (context) {
        TextEditingController addressController = TextEditingController();
        return AlertDialog(
          title: const Text('Add Address'),
          content: TextField(
            controller: addressController,
            decoration: InputDecoration(
              hintText: _selectedAddress,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                String address = addressController.text;
                Navigator.of(context).pop();
              },
              child: const Text('Save'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('Cancel'),
            ),
          ],
        );
      },
    );
  }

  Future<void> getCurrentLocation() async {
    Location location = Location();
    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;
      }
    }

    currentLocation = await location.getLocation();
    setState(() {
      _isLoading = false;
    });
    setState(() {
      _isLoading = false;
      sourceLocation =
          LatLng(currentLocation!.latitude!, currentLocation!.longitude!);
    });

    String apiKey = 'AIz***********************************';
    String url =
        'https://maps.googleapis.com/maps/api/geocode/json?latlng=${currentLocation!.latitude},${currentLocation!.longitude}&key=$apiKey';

    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(response.body);
      if (data['status'] == 'OK') {
        String formattedAddress = data['results'][0]['formatted_address'];
        List<String> addressParts = formattedAddress.split(', ');
        String country = addressParts.last;
        String city = addressParts[addressParts.length - 2];
        String street =
            addressParts.sublist(0, addressParts.length - 2).join(', ');

        setState(() {
          Address = street;
          City = city;
          Country = country;
        });

        List<dynamic> addressComponents =
            data['results'][0]['address_components'];
        String postalCode = '';
        String state = '';

        for (var component in addressComponents) {
          List<dynamic> types = component['types'];
          if (types.contains('postal_code')) {
            postalCode = component['long_name'];
            setState(() {
              Postalcode = postalCode;
            });
          } else if (types.contains('administrative_area_level_1')) {
            state = component['long_name'];
            setState(() {
              State = state;
            });
          }
        }

        setState(() {
          _selectedAddress = '''
$country, $city,
$street
Postal Code: $postalCode
State: $state
''';
        });
      }
    }
  }

  Future<void> animateToCurrentLocation() async {
    if (currentLocation != null) {
      final GoogleMapController controller = await _controller.future;
      controller.animateCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            target: LatLng(
              currentLocation!.latitude!,
              currentLocation!.longitude!,
            ),
            zoom: 10.0,
          ),
        ),
      );
    }
  }

  List<LatLng> polylineCoordinates = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: MYTHEME.APPBAR_COLOR,
        title: const Text('تحديد الموقع الحالي'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Container(
                  color: MYTHEME.APPBAR_COLOR,
                  padding: const EdgeInsets.all(16.0),
                  child: const Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            '1. تحديد العنوان',
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: MYTHEME.MAIN_COLOR),
                          ),
                          Spacer(),
                          Text(
                            'في التقدم',
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: MYTHEME.MAIN_COLOR),
                          ),
                        ],
                      ),
                      SizedBox(height: 8.0),
                      Row(
                        children: [
                          Text(
                            '2. إدخال البيانات',
                            style: TextStyle(
                                fontWeight: FontWeight.bold, color: Colors.red),
                          ),
                          Spacer(),
                          Text(
                            'في التقدم',
                            style: TextStyle(
                                fontWeight: FontWeight.bold, color: Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: GoogleMap(
                    onLongPress: _handleMapLongPress,
                    initialCameraPosition: CameraPosition(
                      target:
                          sourceLocation ?? const LatLng(24.774265, 46.738586),
                      zoom: 13.5,
                    ),
                    markers: {
                      Marker(
                        markerId: const MarkerId("currentLocation"),
                        position: LatLng(currentLocation!.latitude!,
                            currentLocation!.longitude!),
                        infoWindow: const InfoWindow(
                          title: 'موقعك الحالي',
                        ),
                      ),
                    },
                    onMapCreated: (mapController) {
                      _controller.complete(mapController);
                    },
                    polylines: {
                      Polyline(
                        polylineId: const PolylineId("route"),
                        points: polylineCoordinates,
                        color: const Color(0xFF7B61FF),
                        width: 6,
                      ),
                    },
                  ),
                ),
                if (_selectedAddress.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text(_selectedAddress),
                  ),
                SizedBox(
                  width: 180,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          backgroundColor: MYTHEME.MAIN_COLOR),
                      onPressed: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => CreateAccount(
                                      city: City,
                                      country: Country,
                                      postalcode: Postalcode,
                                      state: State,
                                      address: Address,
                                    )));
                      },
                      child: const Padding(
                        padding: EdgeInsets.only(right: 20, left: 20),
                        child: Row(
                          children: [
                            Icon(Icons.arrow_back_ios),
                            Text(
                              'التالي',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 20),
                            )
                          ],
                        ),
                      )),
                )
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          animateToCurrentLocation();
        },
        child: const Icon(Icons.maps_home_work_outlined),
      ),
    );
  }
}

Assuming the API key is setup correctly, do you see any logs about any errors when running it on ios?

I’d start with checking on GCP if both platforms have been enabled. Often you use different keys for ios and android, so just check you’re not using the wrong key on the ios side too. If those are all fine, please provide any logs you’re seeing.

PS: Instead of providing the whole code, since the problem is that the map isn’t showing up, it’d be better if you just gave the google map widget usage rather than everything. Sometimes in making the reproducible sample, you end up finding that it was something else in the code that was actually the problem (unlikely in this case)

When I run the app on xcode, the following message appears:

This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the -locationManagerDidChangeAuthorization: callback and checking authorizationStatus first.

That seems to be coming from your logic to request location permission and fetch the current location. Depends on what package you’re using for that.

Can you remove all that stuff and just have the GoogleMap in your widget tree and see if the map renders. Cause these two seem like different issues