top of page
  • Writer's pictureJohn N Blanchard

Flutter: Geolocation

Mobile apps are able to leverage user location to provide unique features. These features are not delivery as a whole, because the user location can also be conveyed as a street address textfield. Rather having the user's location is a hint; your app can change the curated content without asking the user explicitly to enter an address.

With Flutter we have to start by importing geolocator inside the project's pubspec.yaml; this package will have stuff for prompting the user for location permission, getting the user's location, geocoding, reverse geocoding, and distances between two points. I tested the package using the Android emulator and the iOS simulator. It works very nicely because I am able to see the same experience across platforms.

It takes time to ask the user for permission and to calculate current location, therefore the geolocator package is closely coupled with the async package. We are able to handle future responses from the user and snapshot data from the user's location with a FutureBuilder<T>.

But we first have to describe some futures for this thing to build. I handle the future with a position, if a position is null the user has not yet accepted location permission. With Flutter it felt wildly useful building future dimensions. For example, my app asynchronously waits for the user to respond to location prompt. If the user confirms the permission, I use a nested FutureBuilder<Response> to create some widgets resolving an https call with the user’s coordinates. It is important to not nest FutureBuilders uncessarily because it may only be slowing down the app experience.

When using geolocator specifically with a FutureBuilder<T>, it’s important to understand the closure. The parameter function, or closure has two arguments; one is contextual information about when data was seen, while the other will have physical data at that moment. When querying for the user location, position was my inner T object. The closure houses a context object that knows when data was received, and a snapshot with coordinates.

In the example above we reach the Bart api and curate a list of stations, after receiving station data we are able to kick off a future sorted by the user's distance from each station in the list. This pattern is robust, because I am able to declare UI for multiple user permission paths and nest futures conditionally.

225 views0 comments

Recent Posts

See All
bottom of page