Remy Moll eede94add4
Some checks failed
Build and push docker image / Build (pull_request) Failing after 2m8s
Build and release APK / Build APK (pull_request) Successful in 5m15s
Build web / Build Web (pull_request) Successful in 1m13s
working save and load functionality with custom datastructures
2024-06-23 21:19:06 +02:00

76 lines
1.8 KiB
Dart

// Represents a collection of landmarks that represent a journey
// Different instances of a Trip can be saved and loaded by the user
import 'dart:collection';
import 'dart:convert';
import 'package:fast_network_navigation/structs/landmark.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Trip {
final String uuid;
final String cityName;
// TODO: cityName should be inferred from coordinates of the Landmarks
final LinkedList<Landmark> landmarks;
// could be empty as well
Trip({
required this.uuid,
required this.cityName,
required this.landmarks,
});
factory Trip.fromJson(Map<String, dynamic> json) {
return Trip(
uuid: json['uuid'],
cityName: json['city_name'],
landmarks: LinkedList()
);
}
factory Trip.fromPrefs(SharedPreferences prefs, String uuid) {
String? content = prefs.getString('trip_$uuid');
Map<String, dynamic> json = jsonDecode(content!);
Trip trip = Trip.fromJson(json);
String? firstUUID = json['entry_uuid'];
readLandmarks(trip.landmarks, prefs, firstUUID);
return trip;
}
Map<String, dynamic> toJson() => {
'uuid': uuid,
'city_name': cityName,
'entry_uuid': landmarks.first?.uuid ?? ''
};
void toPrefs(SharedPreferences prefs){
Map<String, dynamic> json = toJson();
prefs.setString('trip_$uuid', jsonEncode(json));
for (Landmark landmark in landmarks) {
landmarkToPrefs(prefs, landmark, landmark.next);
}
}
}
// Helper
readLandmarks(LinkedList<Landmark> landmarks, SharedPreferences prefs, String? firstUUID) {
while (firstUUID != null) {
var (head, nextUUID) = getLandmarkFromPrefs(prefs, firstUUID);
landmarks.add(head);
firstUUID = nextUUID;
}
}
void removeAllTripsFromPrefs () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();
}