'Firestore geoPoint to Flutter nested objects
I would like to create an object from a Firestore doc with a geoPoint. But I keep getting the error: "Failed to get games: type 'GeoPoint' is not a subtype of type 'String?'"
This is my dataset on Firestore:
This is how I query Firestore:
Future<List<GameItem>> getGamesInRegion() async {
List<GameItem> _returnList = [];
await FirebaseFirestore.instance
.collection('games')
.get()
.then((querySnapshot) {
for (var gameItemSnap in querySnapshot.docs) {
_returnList
.add(GameItem.fromJson(gameItemSnap.id, gameItemSnap.data()));
}
}).catchError((error) => debugPrint("Failed to get games: $error"));
return _returnList;
}
This is my GameItem Object:
import 'package:myproj/models/sk_location.dart';
class GameItem {
final String gameId;
final String parentId;
final String name;
final int score;
final SkLocation location;
GameItem({
required this.gameId,
required this.parentId,
required this.name,
required this.score,
required this.location,
});
factory GameItem.fromJson(String id, Map<String, dynamic> parsedJson) {
return GameItem(
gameId: id,
parentId: parsedJson['parentId'] ?? '',
name: parsedJson['name'] ?? '',
score: parsedJson['score'] ?? '',
location: SkLocation.fromJson(parsedJson['geoPoint']),
);
}
toJson() {
return {
"gameId": gameId,
"parentId": parentId,
"name": name,
"score": score,
"location": location,
};
}
}
And this is my SkLocation Object:
class SkLocation {
final double lat;
final double lng;
SkLocation({required this.lat, required this.lng});
factory SkLocation.fromJson(Map<dynamic, dynamic> parsedJson) {
return SkLocation(
lat: parsedJson['lat'],
lng: parsedJson['lng'],
);
}
}
Solution 1:[1]
The Geopoint object in Firestore has two properties: latitude and longitude. In your code you are casting those fields by using lat and lng, that might be the cause of the problem,
So if you were to change your factory in the SkLocation class to the following it should fix the issue:
factory SkLocation.fromJson(Map<dynamic, dynamic> parsedJson) {
return SkLocation(
lat: parsedJson['latitude'],
lng: parsedJson['longitude'],
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ralemos |

