1

I've built a Flutter app using https://pub.dev/packages/google_maps_flutter for maps and I want to add directions as per https://medium.com/@shubham.narkhede8/flutter-google-map-with-direction-6a26ad875083, but I need to get the Google API key, which is injected into the app at build time in different ways depending whether it's Android or IoS.

I've spent about an hour googling, but I can't find a Flutter or native way of getting at the API key in the app. Is there a way?

Paul Grenyer
  • 1,713
  • 3
  • 30
  • 51
  • Can you tell for which purpose you need an API key? – Nikunj Munjiyasara Jul 03 '20 at 09:03
  • Yeah, it's in the second link above: https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=$apiKey – Paul Grenyer Jul 03 '20 at 09:06
  • You get your API key from your Google Cloud Console. Follow the instructions on how to get an API key, this [link](https://developers.google.com/maps/documentation/android-sdk/get-api-key) for android and this [link](https://developers.google.com/maps/documentation/ios-sdk/get-api-key) for iOS. – Akora Ing. DKB Jul 03 '20 at 09:10
  • Nope, getting the API key from google isn't my issue. See above. – Paul Grenyer Jul 03 '20 at 09:11
  • If you added a google map package as per this https://medium.com/@shubham.narkhede8/flutter-google-map-with-direction-6a26ad875083 document then I don't think you don't need to get API key in-app. So Can you explain more about your requirement? – Nikunj Munjiyasara Jul 03 '20 at 09:26
  • If you look further down, the google API Key is hardcoded into the file just before the call to the API to get the directions. I have the maps package, the maps work. – Paul Grenyer Jul 03 '20 at 09:30
  • https://flutter-academy.com/build-flavors-environment-specific-configuration/ not sure if it's the "best" solution but allows you to use a conf file and switch at build which I think it what you're after. I'm imagining using iOS and Android confs for each env.. or something like that. – David McLean Jul 04 '20 at 06:35

1 Answers1

2

If I understand rightly that you're trying to access the Google Maps API key from your native iOS and Android projects from within Flutter, this should work:

Use this: https://pub.dev/packages/flutter_native_config to read the Android manifest and the iOS Info.plist.

On Android the key will already be there as per the Google Maps docs.

You'll then need to move your API key in iOS to the info.plist then read it in instead of having it hardcoded: https://www.hackingwithswift.com/example-code/system/how-to-read-your-apps-version-from-your-infoplist-file

Tom Alabaster
  • 965
  • 6
  • 12