My Google Maps API Key works properly when I hardcode it to the tag like this:
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=HARD_CODED_HERE"></script>
</head>
Now, I don’t want to hard code the value and I need to get it from .env files.
What I have tried and worked so far was:
in the main.dart:
js.context['googleMapsApiKey'] = dotenv.env['GOOGLE_MAPS_API_KEY'];
html.document.dispatchEvent(html.CustomEvent("google-maps-api-key-loaded"));
Basically creating a DOM element for capturing after in the index.html like this:
in the index.html:
<script>
document.addEventListener("google-maps-api-key-loaded", function (){
var googleapis = window.GOOGLE_MAPS_API_KEY;
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=" + googleapis + "&callback=initMap";
script.defer = true;
script.async = true;
document.head.appendChild(script);
});
</script>
The problem is that this solution works only on web because I needed to import these to main.dart:
main.dart file:
import 'dart:js' as js;
import 'dart:html' as html;
Which will not allow iOS and Android to run because these import are intended for web apps, only.
Is any body using similar approach? Or any suggestion for a solution? Preferably without using additional package.
Thanks
2
Answers
In the end, the solution that I've found was installing the package universal_html: https://pub.dev/packages/universal_html
The imports should look like this:
I hope this helps somenone.
hmm so mobile needs the app key.
dart define the app key for mobile. You would need to enter it twice, once in the vscode launch and once in the task part. Then in dart check if not web and read the env key via dart define.