Search code examples
flutterdartlocation

How to get location on app startup to use across app Flutter


I have a few pages that need the user location for calculations but the issue is everytime on these pages Im using the following method everytime I load the screens.

void getCurrentLocation() async {
Location _location = Location();

await _location.getLocation().then(
  (newLocation) {
    setState(() {
      currentLocation = newLocation;
    });
  },
);
}

Is there a way I can run this run once on startup or have it running in the background and access it easily in every page to save on load times? as my app has to load every screen and feels very slow


Solution

  • Try creating a global variable for Location.

    Now, on app init store the current Location in a global variable. & you can use it anywhere.