onLocationChanged
- Flutter course
- Advanced
- Lesson 39/69
- 4 min
Track location continuously with onLocationChanged.
The onLocationChanged stream
onLocationChanged is a stream that emits new location values as the device moves. It returns a Stream<LocationData> and is listened to with listen. It is used instead of getLocation for continuous tracking.
location.onLocationChanged.listen((data) {
print(data.latitude);
});Canceling the subscription
The listen method returns a StreamSubscription. When continuous listening is no longer needed, you cancel the subscription with subscription.cancel(). Otherwise the stream stays open and causes a memory leak.
final sub = location.onLocationChanged.listen((data) {});
// ...
await sub.cancel();Practice Listen to the location stream
Create a Location instance, listen to the onLocationChanged stream with listen and print the incoming latitude. Wait 10 milliseconds.
Starter code
class LocationData {
final double latitude;
LocationData(this.latitude);
}
class Location {
Stream<LocationData> get onLocationChanged => Stream.value(LocationData(41.0));
}
void main() async {
// onLocationChanged akışını dinle
// enlemi yazdır
}Sample solution
class LocationData {
final double latitude;
LocationData(this.latitude);
}
class Location {
Stream<LocationData> get onLocationChanged => Stream.value(LocationData(41.0));
}
void main() async {
final location = Location();
location.onLocationChanged.listen((data) {
print(data.latitude);
});
await Future.delayed(Duration(milliseconds: 10));
}Expected output
41.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does onLocationChanged emit a new value?
- When the app closes
- Only when a button is pressed
- Continuously as the device position changes Correct answer
- Only once, at startup
Explanation: onLocationChanged emits new location values continuously as the device moves; it does not fire once or on button press.
2 Listen to the stream
location.____.listen((data) {
print(data.latitude);
});
location.onLocationChanged.listen((data) {
print(data.latitude);
});
Explanation: onLocationChanged is a getter that returns a Stream; it needs no parentheses and is listened to directly with .listen.
3 onLocationChanged parts
| Term | Meaning |
|---|---|
onLocationChanged |
Location change stream |
listen |
Listens to the stream |
StreamSubscription |
Subscription object |
cancel |
Cancels the subscription |