Update Location with Dart Streams

The flutterlocation package has built in functionality to continuously askthe users device for their location and then execute a callback.

This is done via Streams. In Dart, Streams are a class that allow you to"listen" to a data source and perform an action when the data is updated. Inthis case, we'll listen to the _location given to us by the flutterlocationlibrary, and update our map when it gets a new location.

tldr: There are two parts to using streams.

  • The stream, which emits changes.
  • The subscription, which 'listens' to changes.In depth:

In a chat app, for example, you may have a List of messages between two users.

Whenever a user sends a new message, it will be added to that List. So, youcould set up a stream which will send out a 'broadcast' whenever messages isupdated.

The stream is basically going to say 'Hey, if anyones listening, I just wantyou to know that there is a new message in my list'.

Then, maybe you have a function that is in fact listening (aka subscribed), andwants to create a new 'Text' widget every time a new message is added to thelist. It'll say 'Thanks for the update Stream, I'm going to add a new widgetwith the information from the newest message in that list.'

And that's conceptually what a Stream is, in a nut shell.

1. Add a Listener

First, add a subscription to the location object provided by flutterlocation.

  1. class _MyHomePageState extends State<MyHomePage> {
  2. Location _location = new Location();
  3. StreamSubscription<Map<String, double>> _locationSub; // new
  4. Map<String, double> _currentLocation;
  5. List locations = [];
  6. String googleMapsApi = 'YOUR API KEY';
  7. TextEditingController _latController = new TextEditingController();
  8. TextEditingController _lngController = new TextEditingController();
  9. // All new!
  10. @override
  11. void initState() {
  12. super.initState();
  13. _locationSub =
  14. _location.onLocationChanged.listen((Map<String, double> locationData) {
  15. setState(() {
  16. _currentLocation = {
  17. "latitude": locationData["latitude"],
  18. "longitude": locationData['longitude'],
  19. };
  20. });
  21. });
  22. }

Like I mentioned, the stream is established in the library, so there is verylittle work in making use of this functionality.

This is all you have to do.

Now, when ever the users device's location changes, it'll update the_currentLocation variable in a setState call. That tells flutter to rebuild,and when it does, its with a new _currentLocation.

tip: You can see these changes in your iOS simulator by opening the 'Debug'menu, and selecting 'Location > 'City Bicycle Ride''.