getLocation
- Flutter course
- Advanced
- Lesson 37/69
- 4 min
Get the current location with getLocation.
The getLocation method
The getLocation method reads the device's current position. It is an asynchronous method, so you await it with await, and it returns a LocationData. The first call may be slow because the device gathers the GPS signal.
final data = await location.getLocation();
print(data.latitude);async and await
Because getLocation is asynchronous, the calling function must be marked async and the method must be awaited with await. Otherwise a compile error occurs. This rule applies to all asynchronous operations in Dart.
void main() async {
final data = await location.getLocation();
}Practice Get the location and print it
Create a Location instance, await the location with getLocation and print the latitude.
Starter code
class LocationData {
final double latitude;
final double longitude;
LocationData(this.latitude, this.longitude);
}
class Location {
Future<LocationData> getLocation() async => LocationData(41.0, 29.0);
}
void main() async {
// getLocation ile konum al
// enlemi yazdır
}Sample solution
class LocationData {
final double latitude;
final double longitude;
LocationData(this.latitude, this.longitude);
}
class Location {
Future<LocationData> getLocation() async => LocationData(41.0, 29.0);
}
void main() async {
final location = Location();
final data = await location.getLocation();
print(data.latitude);
}Expected output
41.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the getLocation method return?
- Future<String>
- Stream<LocationData>
- Future<void>
- Future<LocationData> Correct answer
Explanation: getLocation asynchronously returns a LocationData; it is a Future, not a Stream.
2 Call getLocation
final data = await location.____;
final data = await location.getLocation();
Explanation: To get the location you call the getLocation method with parentheses and await it.
3 getLocation parts
| Term | Meaning |
|---|---|
getLocation |
Gets the current location |
await |
Awaits asynchronously |
LocationData |
Location data |
async |
Function marker |