CodeBlanks Logo Icon CodeBlanks

Summary - Location

Combine getLocation and onLocationChanged to make a map view.

Map application

A map application combines getLocation and onLocationChanged. On launch, getLocation reads the initial position and centers the map there. Then the onLocationChanged stream is listened to so the map updates as the device moves.

final initial = await location.getLocation();
print(initial.latitude);
location.onLocationChanged.listen((data) {
  print(data.latitude);
});

Practice Write a map flow

Create a Location instance. First await the initial position with getLocation and print its latitude. Then listen to the onLocationChanged stream and print the incoming latitude. Wait 10 milliseconds.

Starter code

main.dart
class LocationData {
  final double latitude;
  LocationData(this.latitude);
}

class Location {
  Future<LocationData> getLocation() async => LocationData(41.0);
  Stream<LocationData> get onLocationChanged => Stream.value(LocationData(41.5));
}

void main() async {
  // ilk konumu al, yazdır
  // onLocationChanged dinle, yazdır
}

Sample solution

main.dart
class LocationData {
  final double latitude;
  LocationData(this.latitude);
}

class Location {
  Future<LocationData> getLocation() async => LocationData(41.0);
  Stream<LocationData> get onLocationChanged => Stream.value(LocationData(41.5));
}

void main() async {
  final location = Location();
  final initial = await location.getLocation();
  print(initial.latitude);
  location.onLocationChanged.listen((data) {
    print(data.latitude);
  });
  await Future.delayed(Duration(milliseconds: 10));
}

Expected output

41.0
41.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How are getLocation and onLocationChanged used together in a map application?

  • onLocationChanged replaces getLocation
  • Both cannot be called at the same time
  • Only getLocation is used, the stream is ignored
  • getLocation gives the initial position, onLocationChanged tracks movement Correct answer

Explanation: getLocation reads the initial position once, while onLocationChanged emits continuously as the device moves; they are used together.

2 Get the initial position

Question
final initial = await location.____;
Answer
final initial = await location.getLocation();

Explanation: To get the initial position once you call the getLocation method; onLocationChanged is used for the continuous stream.

3 Map parts

Term Meaning
getLocation Initial position
onLocationChanged Continuous tracking
LocationData Location data
listen Listens to the stream

All lessons in Advanced