Compare commits

..

4 Commits

Author SHA1 Message Date
c4fddc1a57 account for changed itineraries once landmarks are marked as done or deleted
Some checks failed
Build and deploy the backend to staging / Build and push image (pull_request) Successful in 1m43s
Run linting on the backend code / Build (pull_request) Successful in 26s
Run testing on the backend code / Build (pull_request) Failing after 3m49s
Build and release debug APK / Build APK (pull_request) Failing after 3m35s
Build and deploy the backend to staging / Deploy to staging (pull_request) Successful in 26s
2025-02-16 12:41:06 +01:00
af5aa0097c reworked page layout inheritence 2025-02-16 11:40:25 +01:00
b82f9997a4 more pleasant progress handling, although somewhat flawed 2025-02-14 12:23:41 +01:00
1d5553f7f2 logger and launch cleanup 2025-02-14 12:14:45 +01:00
24 changed files with 578 additions and 437 deletions

5
.vscode/launch.json vendored
View File

@ -36,7 +36,10 @@
"type": "dart", "type": "dart",
"request": "launch", "request": "launch",
"program": "lib/main.dart", "program": "lib/main.dart",
"cwd": "${workspaceFolder}/frontend" "cwd": "${workspaceFolder}/frontend",
"env": {
"GOOGLE_MAPS_API_KEY": "testing"
}
}, },
{ {
"name": "Frontend - profile", "name": "Frontend - profile",

View File

@ -19,7 +19,7 @@ pluginManagement {
plugins { plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "7.3.0" apply false id "com.android.application" version "8.1.0" apply false
id "org.jetbrains.kotlin.android" version "2.0.20" apply false id "org.jetbrains.kotlin.android" version "2.0.20" apply false
} }

View File

@ -1,72 +1,51 @@
import 'package:anyway/main.dart';
import 'package:anyway/modules/help_dialog.dart';
import 'package:anyway/pages/current_trip.dart';
import 'package:anyway/pages/settings.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/main.dart';
import 'package:anyway/modules/help_dialog.dart';
import 'package:anyway/modules/trips_saved_list.dart'; import 'package:anyway/modules/trips_saved_list.dart';
import 'package:anyway/utils/load_trips.dart';
import 'package:anyway/pages/new_trip_location.dart';
import 'package:anyway/pages/onboarding.dart'; import 'package:anyway/pages/onboarding.dart';
import 'package:anyway/pages/current_trip.dart';
import 'package:anyway/pages/settings.dart';
import 'package:anyway/pages/new_trip_location.dart';
mixin ScaffoldLayout<T extends StatefulWidget> on State<T> {
Widget mainScaffold(
// BasePage is the scaffold that holds a child page and a side drawer BuildContext context,
// The side drawer is the main way to switch between pages {
Widget child = const Text("emptiness"),
class BasePage extends StatefulWidget { Widget title = const Text(APP_NAME),
final Widget mainScreen; List<String> helpTexts = const []
final Widget title; }
final List<String> helpTexts; ) {
const BasePage({
super.key,
required this.mainScreen,
this.title = const Text(APP_NAME),
this.helpTexts = const [],
});
@override
State<BasePage> createState() => _BasePageState();
}
class _BasePageState extends State<BasePage> {
@override
Widget build(BuildContext context) {
savedTrips.loadTrips();
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: widget.title, title: title,
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.help), icon: const Icon(Icons.help),
tooltip: 'Help', tooltip: 'Help',
onPressed: () { onPressed: () {
if (widget.helpTexts.isNotEmpty) { if (helpTexts.isNotEmpty) {
helpDialog(context, widget.helpTexts[0], widget.helpTexts[1]); helpDialog(context, helpTexts[0], helpTexts[1]);
} }
} }
), ),
], ],
), ),
body: Center(child: widget.mainScreen), body: Center(child: child),
drawer: Drawer( drawer: Drawer(
child: Column( child: Column(
children: [ children: [
Container( Container(
decoration: BoxDecoration( decoration: const BoxDecoration(
gradient: APP_GRADIENT, gradient: APP_GRADIENT,
), ),
height: 150, height: 150,
child: Center( child: const Center(
child: Text( child: Text(
APP_NAME, APP_NAME,
style: TextStyle( style: TextStyle(
@ -81,8 +60,7 @@ class _BasePageState extends State<BasePage> {
ListTile( ListTile(
title: const Text('Your Trips'), title: const Text('Your Trips'),
leading: const Icon(Icons.map), leading: const Icon(Icons.map),
// TODO: this is not working! selected: widget is TripPage,
selected: widget.mainScreen is TripPage,
onTap: () {}, onTap: () {},
trailing: ElevatedButton( trailing: ElevatedButton(
onPressed: () { onPressed: () {
@ -111,13 +89,12 @@ class _BasePageState extends State<BasePage> {
const Divider(indent: 10, endIndent: 10), const Divider(indent: 10, endIndent: 10),
ListTile( ListTile(
title: const Text('How to use'), title: const Text('How to use'),
leading: Icon(Icons.help), leading: const Icon(Icons.help),
// TODO: this is not working! selected: widget is OnboardingPage,
selected: widget.mainScreen is OnboardingPage,
onTap: () { onTap: () {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute( MaterialPageRoute(
builder: (context) => OnboardingPage() builder: (context) => const OnboardingPage()
) )
); );
}, },
@ -127,8 +104,7 @@ class _BasePageState extends State<BasePage> {
ListTile( ListTile(
title: const Text('Settings'), title: const Text('Settings'),
leading: const Icon(Icons.settings), leading: const Icon(Icons.settings),
// TODO: this is not working! selected: widget is SettingsPage,
selected: widget.mainScreen is SettingsPage,
onTap: () { onTap: () {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute( MaterialPageRoute(

View File

@ -1,24 +1,27 @@
import 'package:flutter/material.dart';
import 'package:anyway/constants.dart';
import 'package:anyway/utils/get_first_page.dart'; import 'package:anyway/utils/get_first_page.dart';
import 'package:anyway/utils/load_trips.dart'; import 'package:anyway/utils/load_trips.dart';
import 'package:flutter/material.dart';
import 'package:anyway/constants.dart';
void main() => runApp(const App()); void main() => runApp(const App());
// Some global variables
final GlobalKey<ScaffoldMessengerState> rootScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); final GlobalKey<ScaffoldMessengerState> rootScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
final SavedTrips savedTrips = SavedTrips(); final SavedTrips savedTrips = SavedTrips();
// the list of saved trips is then populated implicitly by getFirstPage()
class App extends StatelessWidget { class App extends StatelessWidget {
const App({super.key}); const App({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => MaterialApp(
return MaterialApp( title: APP_NAME,
title: APP_NAME, home: getFirstPage(),
home: getFirstPage(), theme: APP_THEME,
theme: APP_THEME, scaffoldMessengerKey: rootScaffoldMessengerKey
scaffoldMessengerKey: rootScaffoldMessengerKey );
);
}
} }

View File

@ -1,20 +1,18 @@
import 'dart:developer'; import 'dart:developer';
import 'package:anyway/modules/step_between_landmarks.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:anyway/modules/landmark_card.dart';
import 'package:anyway/structs/landmark.dart'; import 'package:anyway/structs/landmark.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:anyway/modules/step_between_landmarks.dart';
import 'package:anyway/modules/landmark_card.dart';
// Returns a list of widgets that represent the landmarks matching the given selector
List<Widget> landmarksList(Trip trip) { List<Widget> landmarksList(Trip trip, {required bool Function(Landmark) selector}) {
log("Trip ${trip.uuid} ${trip.landmarks.length} landmarks");
List<Widget> children = []; List<Widget> children = [];
log("Trip ${trip.uuid} ${trip.landmarks.length} landmarks");
if (trip.landmarks.isEmpty || trip.landmarks.length <= 1 && trip.landmarks.first.type == typeStart ) { if (trip.landmarks.isEmpty || trip.landmarks.length <= 1 && trip.landmarks.first.type == typeStart ) {
children.add( children.add(
const Text("No landmarks in this trip"), const Text("No landmarks in this trip"),
@ -23,17 +21,24 @@ List<Widget> landmarksList(Trip trip) {
} }
for (Landmark landmark in trip.landmarks) { for (Landmark landmark in trip.landmarks) {
children.add( if (selector(landmark)) {
LandmarkCard(landmark, trip),
);
if (landmark.next != null) {
children.add( children.add(
StepBetweenLandmarks(current: landmark, next: landmark.next!) LandmarkCard(landmark, trip),
); );
if (!landmark.visited) {
Landmark? nextLandmark = landmark.next;
while (nextLandmark != null && nextLandmark.visited) {
nextLandmark = nextLandmark.next;
}
if (nextLandmark != null) {
children.add(
StepBetweenLandmarks(current: landmark, next: nextLandmark!)
);
}
}
} }
} }
return children; return children;
} }

View File

@ -1,4 +1,5 @@
import 'package:anyway/constants.dart'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:auto_size_text/auto_size_text.dart'; import 'package:auto_size_text/auto_size_text.dart';
@ -35,29 +36,32 @@ class _CurrentTripLoadingIndicatorState extends State<CurrentTripLoadingIndicato
// In the very center of the panel, show the greeter which tells the user that the trip is being generated // In the very center of the panel, show the greeter which tells the user that the trip is being generated
Center(child: loadingText(widget.trip)), Center(child: loadingText(widget.trip)),
// As a gimmick, and a way to show that the app is still working, show a few loading dots // As a gimmick, and a way to show that the app is still working, show a few loading dots
Align( const Align(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
child: statusText(), child: Padding(
padding: EdgeInsets.only(bottom: 12),
child: StatusText(),
)
) )
], ],
); );
} }
// automatically cycle through the greeter texts // automatically cycle through the greeter texts
class statusText extends StatefulWidget { class StatusText extends StatefulWidget {
const statusText({Key? key}) : super(key: key); const StatusText({Key? key}) : super(key: key);
@override @override
_statusTextState createState() => _statusTextState(); _StatusTextState createState() => _StatusTextState();
} }
class _statusTextState extends State<statusText> { class _StatusTextState extends State<StatusText> {
int statusIndex = 0; int statusIndex = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
Future.delayed(Duration(seconds: 5), () { Future.delayed(const Duration(seconds: 5), () {
setState(() { setState(() {
statusIndex = (statusIndex + 1) % statusTexts.length; statusIndex = (statusIndex + 1) % statusTexts.length;
}); });
@ -81,19 +85,19 @@ Widget loadingText(Trip trip) => FutureBuilder(
Widget greeter; Widget greeter;
if (snapshot.hasData) { if (snapshot.hasData) {
greeter = AnimatedGradientText( greeter = AnimatedDotsText(
text: 'Creating your trip to ${snapshot.data}...', baseText: 'Creating your trip to ${snapshot.data}',
style: greeterStyle, style: greeterStyle,
); );
} else if (snapshot.hasError) { } else if (snapshot.hasError) {
// the exact error is shown in the central part of the trip overview. No need to show it here // the exact error is shown in the central part of the trip overview. No need to show it here
greeter = AnimatedGradientText( greeter = Text(
text: 'Error while loading trip.', 'Error while loading trip.',
style: greeterStyle, style: greeterStyle,
); );
} else { } else {
greeter = AnimatedGradientText( greeter = AnimatedDotsText(
text: 'Creating your trip...', baseText: 'Creating your trip',
style: greeterStyle, style: greeterStyle,
); );
} }
@ -101,62 +105,44 @@ Widget loadingText(Trip trip) => FutureBuilder(
} }
); );
class AnimatedGradientText extends StatefulWidget { class AnimatedDotsText extends StatefulWidget {
final String text; final String baseText;
final TextStyle style; final TextStyle style;
const AnimatedGradientText({ const AnimatedDotsText({
Key? key, Key? key,
required this.text, required this.baseText,
required this.style, required this.style,
}) : super(key: key); }) : super(key: key);
@override @override
_AnimatedGradientTextState createState() => _AnimatedGradientTextState(); _AnimatedDotsTextState createState() => _AnimatedDotsTextState();
} }
class _AnimatedGradientTextState extends State<AnimatedGradientText> with SingleTickerProviderStateMixin { class _AnimatedDotsTextState extends State<AnimatedDotsText> {
late AnimationController _controller; int dotCount = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_controller = AnimationController( Timer.periodic(const Duration(seconds: 1), (timer) {
duration: const Duration(seconds: 1), if (mounted) {
vsync: this, setState(() {
)..repeat(); dotCount = (dotCount + 1) % 4;
} // show up to 3 dots
});
@override } else {
void dispose() { timer.cancel();
_controller.dispose(); }
super.dispose(); });
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AnimatedBuilder( String dots = '.' * dotCount;
animation: _controller, return Text(
builder: (context, child) { '${widget.baseText}$dots',
return ShaderMask( style: widget.style,
shaderCallback: (bounds) {
return LinearGradient(
colors: [GRADIENT_START, GRADIENT_END, GRADIENT_START],
stops: [
_controller.value - 1.0,
_controller.value,
_controller.value + 1.0,
],
tileMode: TileMode.mirror,
).createShader(bounds);
},
child: Text(
widget.text,
style: widget.style,
),
);
},
); );
} }
} }

View File

@ -1,22 +1,19 @@
import 'dart:collection'; import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:widget_to_marker/widget_to_marker.dart';
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import 'package:anyway/modules/landmark_map_marker.dart';
import 'package:flutter/material.dart';
import 'package:anyway/structs/landmark.dart'; import 'package:anyway/structs/landmark.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:anyway/modules/landmark_map_marker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:widget_to_marker/widget_to_marker.dart';
class CurrentTripMap extends StatefulWidget { class CurrentTripMap extends StatefulWidget {
final Trip? trip; final Trip? trip;
CurrentTripMap({ CurrentTripMap({this.trip});
this.trip
});
@override @override
State<CurrentTripMap> createState() => _CurrentTripMapState(); State<CurrentTripMap> createState() => _CurrentTripMapState();
@ -30,7 +27,23 @@ class _CurrentTripMapState extends State<CurrentTripMap> {
zoom: 11.0, zoom: 11.0,
); );
Set<Marker> mapMarkers = <Marker>{}; Set<Marker> mapMarkers = <Marker>{};
Set<Polyline> mapPolylines = <Polyline>{};
@override
void initState() {
super.initState();
widget.trip?.addListener(setMapMarkers);
widget.trip?.addListener(setMapRoute);
}
@override
void dispose() {
widget.trip?.removeListener(setMapMarkers);
widget.trip?.removeListener(setMapRoute);
super.dispose();
}
void _onMapCreated(GoogleMapController controller) async { void _onMapCreated(GoogleMapController controller) async {
mapController = controller; mapController = controller;
@ -40,38 +53,70 @@ class _CurrentTripMapState extends State<CurrentTripMap> {
controller.moveCamera(update); controller.moveCamera(update);
} }
setMapMarkers(); setMapMarkers();
setMapRoute();
} }
void _onCameraIdle() { void _onCameraIdle() {
// print(mapController.getLatLng(ScreenCoordinate(x: 0, y: 0))); // print(mapController.getLatLng(ScreenCoordinate(x: 0, y: 0)));
} }
void setMapMarkers() async { void setMapMarkers() async {
List<Landmark> landmarks = widget.trip?.landmarks.toList() ?? []; Iterator<(int, Landmark)> it = (widget.trip?.landmarks.toList() ?? []).indexed.iterator;
Set<Marker> newMarkers = <Marker>{};
for (int i = 0; i < landmarks.length; i++) { while (it.moveNext()) {
Landmark landmark = landmarks[i]; int i = it.current.$1;
Landmark landmark = it.current.$2;
MarkerId markerId = MarkerId("${landmark.uuid} - ${landmark.visited}");
List<double> location = landmark.location; List<double> location = landmark.location;
Marker marker = Marker( // only create a new marker, if there is no marker for this landmark
markerId: MarkerId(landmark.uuid), if (!mapMarkers.any((Marker marker) => marker.markerId == markerId)) {
position: LatLng(location[0], location[1]), Marker marker = Marker(
icon: await ThemedMarker(landmark: landmark, position: i).toBitmapDescriptor( markerId: markerId,
logicalSize: const Size(150, 150), position: LatLng(location[0], location[1]),
imageSize: const Size(150, 150) icon: await ThemedMarker(landmark: landmark, position: i).toBitmapDescriptor(
), logicalSize: const Size(150, 150),
); imageSize: const Size(150, 150),
newMarkers.add(marker); )
);
setState(() {
mapMarkers.add(marker);
});
}
} }
}
void setMapRoute() async {
List<Landmark> landmarks = widget.trip?.landmarks.toList() ?? [];
Set<Polyline> polyLines = <Polyline>{};
if (landmarks.length < 2) {
return;
}
for (Landmark landmark in landmarks) {
if (landmark.next != null) {
List<LatLng> step = [
LatLng(landmark.location[0], landmark.location[1]),
LatLng(landmark.next!.location[0], landmark.next!.location[1])
];
Polyline stepLine = Polyline(
polylineId: PolylineId('step-${landmark.uuid}'),
points: step,
color: landmark.visited || (landmark.next?.visited ?? false) ? Colors.grey : PRIMARY_COLOR,
width: 5
);
polyLines.add(stepLine);
}
}
setState(() { setState(() {
mapMarkers = newMarkers; mapPolylines = polyLines;
}); });
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
widget.trip?.addListener(setMapMarkers);
Future<SharedPreferences> preferences = SharedPreferences.getInstance(); Future<SharedPreferences> preferences = SharedPreferences.getInstance();
return FutureBuilder( return FutureBuilder(
@ -84,7 +129,7 @@ class _CurrentTripMapState extends State<CurrentTripMap> {
} else { } else {
return const CircularProgressIndicator(); return const CircularProgressIndicator();
} }
} },
); );
} }
@ -93,8 +138,8 @@ class _CurrentTripMapState extends State<CurrentTripMap> {
onMapCreated: _onMapCreated, onMapCreated: _onMapCreated,
initialCameraPosition: _cameraPosition, initialCameraPosition: _cameraPosition,
onCameraIdle: _onCameraIdle, onCameraIdle: _onCameraIdle,
// onLongPress: ,
markers: mapMarkers, markers: mapMarkers,
polylines: mapPolylines,
cloudMapId: MAP_ID, cloudMapId: MAP_ID,
mapToolbarEnabled: false, mapToolbarEnabled: false,
zoomControlsEnabled: false, zoomControlsEnabled: false,
@ -102,5 +147,4 @@ class _CurrentTripMapState extends State<CurrentTripMap> {
myLocationButtonEnabled: false, myLocationButtonEnabled: false,
); );
} }
} }

View File

@ -1,9 +1,12 @@
import 'package:anyway/constants.dart';
import 'package:anyway/modules/current_trip_error_message.dart';
import 'package:anyway/modules/current_trip_loading_indicator.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:anyway/constants.dart';
import 'package:anyway/structs/landmark.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:anyway/modules/current_trip_error_message.dart';
import 'package:anyway/modules/current_trip_loading_indicator.dart';
import 'package:anyway/modules/current_trip_summary.dart'; import 'package:anyway/modules/current_trip_summary.dart';
import 'package:anyway/modules/current_trip_save_button.dart'; import 'package:anyway/modules/current_trip_save_button.dart';
import 'package:anyway/modules/current_trip_landmarks_list.dart'; import 'package:anyway/modules/current_trip_landmarks_list.dart';
@ -63,13 +66,41 @@ class _CurrentTripPanelState extends State<CurrentTripPanel> {
child: CurrentTripGreeter(trip: widget.trip), child: CurrentTripGreeter(trip: widget.trip),
), ),
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: [
CurrentTripSummary(trip: widget.trip),
if (widget.trip.landmarks.where((Landmark landmark) => landmark.visited).isNotEmpty)
ExpansionTile(
leading: const Icon(Icons.location_on),
title: const Text('Visited Landmarks (tap to expand)'),
children: [
...landmarksList(widget.trip, selector: (Landmark landmark) => landmark.visited),
],
visualDensity: VisualDensity.compact,
collapsedShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
],
),
),
),
const Padding(padding: EdgeInsets.only(top: 10)), const Padding(padding: EdgeInsets.only(top: 10)),
// CurrentTripSummary(trip: widget.trip), // upcoming landmarks
...landmarksList(widget.trip, selector: (Landmark landmark) => landmark.visited == false),
// const Divider(),
...landmarksList(widget.trip),
const Padding(padding: EdgeInsets.only(top: 10)), const Padding(padding: EdgeInsets.only(top: 10)),

View File

@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:anyway/main.dart'; import 'package:anyway/main.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
class saveButton extends StatefulWidget { class saveButton extends StatefulWidget {
@ -52,4 +52,3 @@ class _saveButtonState extends State<saveButton> {
); );
} }
} }

View File

@ -1,6 +1,7 @@
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class CurrentTripSummary extends StatefulWidget { class CurrentTripSummary extends StatefulWidget {
final Trip trip; final Trip trip;
const CurrentTripSummary({ const CurrentTripSummary({
@ -15,17 +16,27 @@ class CurrentTripSummary extends StatefulWidget {
class _CurrentTripSummaryState extends State<CurrentTripSummary> { class _CurrentTripSummaryState extends State<CurrentTripSummary> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( return Padding(
children: [ padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
Text('Summary'), child: Row(
// Text('Start: ${widget.trip.start}'), mainAxisAlignment: MainAxisAlignment.spaceBetween,
// Text('End: ${widget.trip.end}'), children: [
Text('Total duration: ${widget.trip.totalTime}'), Row(
Text('Total distance: ${widget.trip.totalTime}'), children: [
// Text('Fuel: ${widget.trip.fuel}'), const Icon(Icons.flag, size: 20),
// Text('Cost: ${widget.trip.cost}'), const Padding(padding: EdgeInsets.only(right: 10)),
], Text('Stops: ${widget.trip.landmarks.length}', style: Theme.of(context).textTheme.bodyLarge),
]
),
Row(
children: [
const Icon(Icons.hourglass_bottom_rounded, size: 20),
const Padding(padding: EdgeInsets.only(right: 10)),
Text('Duration: ${widget.trip.totalTime} minutes', style: Theme.of(context).textTheme.bodyLarge),
]
),
],
)
); );
} }
} }

View File

@ -1,6 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
Future<void> helpDialog(BuildContext context, String title, String content) { Future<void> helpDialog(BuildContext context, String title, String content) {
return showDialog<void>( return showDialog<void>(
context: context, context: context,

View File

@ -1,11 +1,15 @@
import 'package:anyway/main.dart';
import 'package:anyway/structs/trip.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:anyway/constants.dart';
import 'package:anyway/main.dart';
import 'package:anyway/structs/trip.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:anyway/structs/landmark.dart'; import 'package:anyway/structs/landmark.dart';
class LandmarkCard extends StatefulWidget { class LandmarkCard extends StatefulWidget {
final Landmark landmark; final Landmark landmark;
final Trip parentTrip; final Trip parentTrip;
@ -13,7 +17,7 @@ class LandmarkCard extends StatefulWidget {
LandmarkCard( LandmarkCard(
this.landmark, this.landmark,
this.parentTrip, this.parentTrip,
); );
@override @override
_LandmarkCardState createState() => _LandmarkCardState(); _LandmarkCardState createState() => _LandmarkCardState();
@ -23,150 +27,184 @@ class LandmarkCard extends StatefulWidget {
class _LandmarkCardState extends State<LandmarkCard> { class _LandmarkCardState extends State<LandmarkCard> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.landmark.type == typeStart || widget.landmark.type == typeFinish) {
return TextButton.icon(
onPressed: () {},
icon: widget.landmark.type.icon,
label: Text(widget.landmark.name),
);
}
// else:
return Container( return Container(
constraints: BoxConstraints(
// express the max height in terms text lines
maxHeight: 7 * (Theme.of(context).textTheme.titleMedium!.fontSize! + 10),
),
child: Card( child: Card(
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0), borderRadius: BorderRadius.circular(15.0),
), ),
elevation: 5, elevation: 5,
clipBehavior: Clip.antiAliasWithSaveLayer, clipBehavior: Clip.antiAliasWithSaveLayer,
// if the image is available, display it on the left side of the card, otherwise only display the text // if the image is available, display it on the left side of the card, otherwise only display the text
child: widget.landmark.imageURL != null ? splitLayout() : textLayout(), child: Row(
), crossAxisAlignment: CrossAxisAlignment.start,
); children: [
} // Image and landmark "type" on the left
AspectRatio(
Widget splitLayout() { aspectRatio: 3 / 4,
// If an image is available, display it on the left side of the card child: Column(
return Row( crossAxisAlignment: CrossAxisAlignment.stretch,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
// the image on the left
width: 160,
height: 160,
child: CachedNetworkImage(
imageUrl: widget.landmark.imageURL ?? '',
placeholder: (context, url) => Center(child: CircularProgressIndicator()),
errorWidget: (context, error, stackTrace) => Icon(Icons.question_mark_outlined),
fit: BoxFit.cover,
),
),
Flexible(
child: textLayout(),
),
],
);
}
Widget textLayout() {
return Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
Row(
children: [
Flexible(
child: Text(
widget.landmark.name,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
maxLines: 2,
),
)
],
),
if (widget.landmark.nameEN != null)
Row(
children: [
Flexible(
child: Text(
widget.landmark.nameEN!,
style: const TextStyle(
fontSize: 16,
),
maxLines: 1,
),
)
],
),
Padding(padding: EdgeInsets.only(top: 10)),
Align(
alignment: Alignment.centerLeft,
child: SingleChildScrollView(
// allows the buttons to be scrolled
scrollDirection: Axis.horizontal,
child: Wrap(
spacing: 10,
// show the type, the website, and the wikipedia link as buttons/labels in a row
children: [ children: [
TextButton.icon( if (widget.landmark.imageURL != null && widget.landmark.imageURL!.isNotEmpty)
onPressed: () {}, Expanded(
icon: widget.landmark.type.icon, child: CachedNetworkImage(
label: Text(widget.landmark.type.name), imageUrl: widget.landmark.imageURL!,
), placeholder: (context, url) => const Center(child: CircularProgressIndicator()),
if (widget.landmark.duration != null && widget.landmark.duration!.inMinutes > 0) errorWidget: (context, url, error) => imagePlaceholder(widget.landmark),
TextButton.icon( fit: BoxFit.cover
onPressed: () {}, )
icon: Icon(Icons.hourglass_bottom), )
label: Text('${widget.landmark.duration!.inMinutes} minutes'), else
), imagePlaceholder(widget.landmark),
if (widget.landmark.websiteURL != null)
TextButton.icon(
onPressed: () async {
// open a browser with the website link
await launchUrl(Uri.parse(widget.landmark.websiteURL!));
},
icon: Icon(Icons.link),
label: Text('Website'),
),
PopupMenuButton(
icon: Icon(Icons.settings),
style: TextButtonTheme.of(context).style,
itemBuilder: (context) => [
PopupMenuItem(
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Delete'),
onTap: () async {
widget.parentTrip.removeLandmark(widget.landmark);
rootScaffoldMessengerKey.currentState!.showSnackBar(
SnackBar(content: Text("We won't show ${widget.landmark.name} again"))
);
},
),
),
PopupMenuItem(
child: ListTile(
leading: Icon(Icons.star),
title: Text('Favorite'),
onTap: () async {
// delete the landmark
// await deleteLandmark(widget.landmark);
},
),
),
],
)
if (widget.landmark.type != typeStart && widget.landmark.type != typeFinish)
Container(
color: PRIMARY_COLOR,
child: Center(
child: Padding(
padding: EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
spacing: 5,
children: [
Icon(Icons.timer_outlined, size: 16),
Text("${widget.landmark.duration?.inMinutes} minutes"),
],
)
)
),
)
], ],
), )
), ),
),
], // Main information, useful buttons on the right
), Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.landmark.name,
style: Theme.of(context).textTheme.titleMedium,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
if (widget.landmark.nameEN != null)
Text(
widget.landmark.nameEN!,
style: Theme.of(context).textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
]
),
),
// fill the vspace
const Spacer(),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: EdgeInsets.only(left: 5, right: 5, bottom: 10),
// the scroll view should be flush once the buttons are scrolled to the left
// but initially there should be some padding
child: Wrap(
spacing: 10,
// show the type, the website, and the wikipedia link as buttons/labels in a row
children: [
doneToggleButton(),
if (widget.landmark.websiteURL != null)
websiteButton(),
optionsButton()
],
),
),
],
)
)
],
)
)
); );
} }
Widget doneToggleButton() {
return TextButton.icon(
onPressed: () async {
widget.landmark.visited = !widget.landmark.visited;
widget.parentTrip.notifyUpdate();
},
icon: Icon(widget.landmark.visited ? Icons.undo_sharp : Icons.check),
label: Text(widget.landmark.visited ? "Add to overview" : "Done!"),
);
}
Widget websiteButton () => TextButton.icon(
onPressed: () async {
// open a browser with the website link
await launchUrl(Uri.parse(widget.landmark.websiteURL!));
},
icon: const Icon(Icons.link),
label: const Text('Website'),
);
Widget optionsButton () => PopupMenuButton(
icon: const Icon(Icons.settings),
style: TextButtonTheme.of(context).style,
itemBuilder: (context) => [
PopupMenuItem(
child: ListTile(
leading: const Icon(Icons.delete),
title: const Text('Delete'),
onTap: () async {
widget.parentTrip.removeLandmark(widget.landmark);
rootScaffoldMessengerKey.currentState!.showSnackBar(
SnackBar(content: Text("${widget.landmark.name} won't be shown again"))
);
},
),
),
PopupMenuItem(
child: ListTile(
leading: const Icon(Icons.star),
title: const Text('Favorite'),
onTap: () async {
rootScaffoldMessengerKey.currentState!.showSnackBar(
SnackBar(content: Text("Not implemented yet"))
);
},
),
),
],
);
} }
Widget imagePlaceholder (Landmark landmark) => Expanded(
child:
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [GRADIENT_START, GRADIENT_END],
),
),
child: Center(
child: Icon(landmark.type.icon.icon, size: 50),
),
),
);

View File

@ -40,7 +40,7 @@ class ThemedMarker extends StatelessWidget {
children: [ children: [
Container( Container(
decoration: BoxDecoration( decoration: BoxDecoration(
gradient: APP_GRADIENT, gradient: landmark.visited ? LinearGradient(colors: [Colors.grey, Colors.white]) : APP_GRADIENT,
shape: BoxShape.circle, shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 5), border: Border.all(color: Colors.black, width: 5),
), ),

View File

@ -46,11 +46,11 @@ class _NewTripButtonState extends State<NewTripButton> {
UserPreferences preferences = widget.preferences; UserPreferences preferences = widget.preferences;
if (preferences.nature.value == 0 && preferences.shopping.value == 0 && preferences.sightseeing.value == 0){ if (preferences.nature.value == 0 && preferences.shopping.value == 0 && preferences.sightseeing.value == 0){
rootScaffoldMessengerKey.currentState!.showSnackBar( rootScaffoldMessengerKey.currentState!.showSnackBar(
SnackBar(content: Text("Please specify at least one preference")) const SnackBar(content: Text("Please specify at least one preference"))
); );
} else if (preferences.maxTime.value == 0){ } else if (preferences.maxTime.value == 0){
rootScaffoldMessengerKey.currentState!.showSnackBar( rootScaffoldMessengerKey.currentState!.showSnackBar(
SnackBar(content: Text("Please choose a longer duration")) const SnackBar(content: Text("Please choose a longer duration"))
); );
} else { } else {
Trip trip = widget.trip; Trip trip = widget.trip;
@ -63,4 +63,3 @@ class _NewTripButtonState extends State<NewTripButton> {
} }
} }
} }

View File

@ -1,14 +1,14 @@
// A map that allows the user to select a location for a new trip. // A map that allows the user to select a location for a new trip.
import 'dart:developer'; import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:widget_to_marker/widget_to_marker.dart';
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import 'package:anyway/modules/landmark_map_marker.dart';
import 'package:anyway/structs/landmark.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:flutter/material.dart'; import 'package:anyway/structs/landmark.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:anyway/modules/landmark_map_marker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:widget_to_marker/widget_to_marker.dart';
class NewTripMap extends StatefulWidget { class NewTripMap extends StatefulWidget {
@ -30,7 +30,6 @@ class _NewTripMapState extends State<NewTripMap> {
final Set<Marker> _markers = <Marker>{}; final Set<Marker> _markers = <Marker>{};
_onLongPress(LatLng location) { _onLongPress(LatLng location) {
log('Long press: $location');
widget.trip.landmarks.clear(); widget.trip.landmarks.clear();
widget.trip.addLandmark( widget.trip.addLandmark(
Landmark( Landmark(

View File

@ -1,7 +1,9 @@
import 'package:anyway/structs/landmark.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:anyway/structs/landmark.dart';
import 'package:anyway/modules/map_chooser.dart'; import 'package:anyway/modules/map_chooser.dart';
class StepBetweenLandmarks extends StatefulWidget { class StepBetweenLandmarks extends StatefulWidget {
final Landmark current; final Landmark current;
final Landmark next; final Landmark next;
@ -19,12 +21,23 @@ class StepBetweenLandmarks extends StatefulWidget {
class _StepBetweenLandmarksState extends State<StepBetweenLandmarks> { class _StepBetweenLandmarksState extends State<StepBetweenLandmarks> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
int timeRounded = 5 * ((widget.current.tripTime?.inMinutes ?? 0) ~/ 5); int? time = widget.current.tripTime?.inMinutes;
// ~/ is integer division (rounding)
// since landmarks might have been marked as visited, the next landmark might not be the immediate next in the list
// => the precomputed trip time is not valid anymore
if (widget.current.next != widget.next) {
time = null;
}
// round 0 travel time to 1 minute
if (time != null && time < 1) {
time = 1;
}
return Container( return Container(
margin: EdgeInsets.all(10), margin: const EdgeInsets.all(10),
padding: EdgeInsets.all(10), padding: const EdgeInsets.all(10),
decoration: BoxDecoration( decoration: const BoxDecoration(
border: Border( border: Border(
left: BorderSide(width: 3.0, color: Colors.black), left: BorderSide(width: 3.0, color: Colors.black),
), ),
@ -33,21 +46,22 @@ class _StepBetweenLandmarksState extends State<StepBetweenLandmarks> {
children: [ children: [
Column( Column(
children: [ children: [
Icon(Icons.directions_walk), const Icon(Icons.directions_walk),
Text("~$timeRounded min", style: TextStyle(fontSize: 10)), Text(
time == null ? "" : "About $time min",
style: const TextStyle(fontSize: 10)
),
], ],
), ),
Spacer(),
ElevatedButton( const Spacer(),
ElevatedButton.icon(
onPressed: () async { onPressed: () async {
showMapChooser(context, widget.current, widget.next); showMapChooser(context, widget.current, widget.next);
}, },
child: Row( icon: const Icon(Icons.directions),
children: [ label: const Text("Directions"),
Icon(Icons.directions),
Text("Directions"),
],
),
) )
], ],
), ),

View File

@ -1,5 +1,5 @@
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import 'package:anyway/pages/base_page.dart'; import 'package:anyway/layouts/scaffold.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart';
@ -28,12 +28,13 @@ class TripPage extends StatefulWidget {
class _TripPageState extends State<TripPage> { class _TripPageState extends State<TripPage> with ScaffoldLayout{
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BasePage( return mainScaffold(
mainScreen: SlidingUpPanel( context,
child: SlidingUpPanel(
// use panelBuilder instead of panel so that we can reuse the scrollcontroller for the listview // use panelBuilder instead of panel so that we can reuse the scrollcontroller for the listview
panelBuilder: (scrollcontroller) => CurrentTripPanel(controller: scrollcontroller, trip: widget.trip), panelBuilder: (scrollcontroller) => CurrentTripPanel(controller: scrollcontroller, trip: widget.trip),
// using collapsed and panelBuilder seems to show both at the same time, so we include the greeter in the panelBuilder // using collapsed and panelBuilder seems to show both at the same time, so we include the greeter in the panelBuilder
@ -58,9 +59,13 @@ class _TripPageState extends State<TripPage> {
title: FutureBuilder( title: FutureBuilder(
future: widget.trip.cityName, future: widget.trip.cityName,
builder: (context, snapshot) => Text( builder: (context, snapshot) => Text(
'Your trip to ${snapshot.hasData ? snapshot.data! : "..."}', 'Trip to ${snapshot.hasData ? snapshot.data! : "..."}',
) )
), ),
helpTexts: [
'Current trip',
'You can see and edit your current trip here. Swipe up from the bottom to see a detailed view of the recommendations.'
],
); );
} }
} }

View File

@ -1,5 +1,5 @@
import 'package:anyway/layouts/scaffold.dart';
import 'package:anyway/modules/new_trip_options_button.dart'; import 'package:anyway/modules/new_trip_options_button.dart';
import 'package:anyway/pages/base_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import "package:anyway/structs/trip.dart"; import "package:anyway/structs/trip.dart";
@ -14,7 +14,7 @@ class NewTripPage extends StatefulWidget {
_NewTripPageState createState() => _NewTripPageState(); _NewTripPageState createState() => _NewTripPageState();
} }
class _NewTripPageState extends State<NewTripPage> { class _NewTripPageState extends State<NewTripPage> with ScaffoldLayout {
final TextEditingController latController = TextEditingController(); final TextEditingController latController = TextEditingController();
final TextEditingController lonController = TextEditingController(); final TextEditingController lonController = TextEditingController();
Trip trip = Trip(); Trip trip = Trip();
@ -23,8 +23,9 @@ class _NewTripPageState extends State<NewTripPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// floating search bar and map as a background // floating search bar and map as a background
return BasePage( return mainScaffold(
mainScreen: Scaffold( context,
child: Scaffold(
body: Stack( body: Stack(
children: [ children: [
NewTripMap(trip), NewTripMap(trip),

View File

@ -1,5 +1,5 @@
import 'package:anyway/layouts/scaffold.dart';
import 'package:anyway/modules/new_trip_button.dart'; import 'package:anyway/modules/new_trip_button.dart';
import 'package:anyway/pages/base_page.dart';
import 'package:anyway/structs/preferences.dart'; import 'package:anyway/structs/preferences.dart';
import 'package:anyway/structs/trip.dart'; import 'package:anyway/structs/trip.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
@ -15,13 +15,14 @@ class NewTripPreferencesPage extends StatefulWidget {
_NewTripPreferencesPageState createState() => _NewTripPreferencesPageState(); _NewTripPreferencesPageState createState() => _NewTripPreferencesPageState();
} }
class _NewTripPreferencesPageState extends State<NewTripPreferencesPage> { class _NewTripPreferencesPageState extends State<NewTripPreferencesPage> with ScaffoldLayout {
UserPreferences preferences = UserPreferences(); UserPreferences preferences = UserPreferences();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BasePage( return mainScaffold(
mainScreen: Scaffold( context,
child: Scaffold(
body: ListView( body: ListView(
children: [ children: [
// Center( // Center(
@ -41,23 +42,22 @@ class _NewTripPreferencesPageState extends State<NewTripPreferencesPage> {
// ) // )
// ), // ),
Center( Center(
child: Padding( child: Padding(
padding: EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 0), padding: EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 0),
child: Text('Tell us about your ideal trip.', style: TextStyle(fontSize: 18)) child: Text('Tell us about your ideal trip.', style: TextStyle(fontSize: 18))
),
), ),
),
Divider(indent: 25, endIndent: 25, height: 50), Divider(indent: 25, endIndent: 25, height: 50),
durationPicker(preferences.maxTime), durationPicker(preferences.maxTime),
preferenceSliders([preferences.sightseeing, preferences.shopping, preferences.nature]), preferenceSliders([preferences.sightseeing, preferences.shopping, preferences.nature]),
] ]
), ),
floatingActionButton: NewTripButton(trip: widget.trip, preferences: preferences), floatingActionButton: NewTripButton(trip: widget.trip, preferences: preferences),
), ),
title: FutureBuilder( title: FutureBuilder(
future: widget.trip.cityName, future: widget.trip.cityName,
builder: (context, snapshot) => Text( builder: (context, snapshot) => Text(

View File

@ -1,6 +1,6 @@
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import 'package:anyway/layouts/scaffold.dart';
import 'package:anyway/main.dart'; import 'package:anyway/main.dart';
import 'package:anyway/pages/base_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -14,42 +14,41 @@ class SettingsPage extends StatefulWidget {
_SettingsPageState createState() => _SettingsPageState(); _SettingsPageState createState() => _SettingsPageState();
} }
class _SettingsPageState extends State<SettingsPage> { class _SettingsPageState extends State<SettingsPage> with ScaffoldLayout {
@override @override
Widget build(BuildContext context) { Widget build (BuildContext context) => mainScaffold(
return BasePage( context,
mainScreen: ListView( child: ListView(
padding: EdgeInsets.all(15), padding: EdgeInsets.all(15),
children: [ children: [
// First a round, centered image // First a round, centered image
Center( Center(
child: CircleAvatar( child: CircleAvatar(
radius: 75, radius: 75,
child: Icon(Icons.settings, size: 100), child: Icon(Icons.settings, size: 100),
) )
), ),
Center( Center(
child: Text('Global settings', style: TextStyle(fontSize: 24)) child: Text('Global settings', style: TextStyle(fontSize: 24))
), ),
Divider(indent: 25, endIndent: 25, height: 50), Divider(indent: 25, endIndent: 25, height: 50),
darkMode(), darkMode(),
setLocationUsage(), setLocationUsage(),
setDebugMode(), setDebugMode(),
Divider(indent: 25, endIndent: 25, height: 50), Divider(indent: 25, endIndent: 25, height: 50),
privacyInfo(), privacyInfo(),
] ]
), ),
title: Text('Settings'), title: Text('Settings'),
helpTexts: [ helpTexts: [
'Settings', 'Settings',
'Preferences set in this page are global and will affect the entire application.' 'Preferences set in this page are global and will affect the entire application.'
], ],
); );
}
Widget setDebugMode() { Widget setDebugMode() {
return Row( return Row(

View File

@ -27,11 +27,12 @@ final class Landmark extends LinkedListEntry<Landmark>{
String? imageURL; // not final because it can be patched String? imageURL; // not final because it can be patched
final String? description; final String? description;
final Duration? duration; final Duration? duration;
final bool? visited; bool visited;
// Next node // Next node is implicitly available through the LinkedListEntry mixin
// final Landmark? next; // final Landmark? next;
final Duration? tripTime; Duration? tripTime;
// the trip time depends on the next landmark, so it is not final
Landmark({ Landmark({
@ -46,7 +47,7 @@ final class Landmark extends LinkedListEntry<Landmark>{
this.imageURL, this.imageURL,
this.description, this.description,
this.duration, this.duration,
this.visited, this.visited = false,
// this.next, // this.next,
this.tripTime, this.tripTime,
@ -70,8 +71,8 @@ final class Landmark extends LinkedListEntry<Landmark>{
final websiteURL = json['website_url'] as String?; final websiteURL = json['website_url'] as String?;
final imageURL = json['image_url'] as String?; final imageURL = json['image_url'] as String?;
final description = json['description'] as String?; final description = json['description'] as String?;
var duration = Duration(minutes: json['duration'] ?? 0) as Duration?; var duration = Duration(minutes: json['duration']);
final visited = json['visited'] as bool?; final visited = json['visited'] ?? false;
var tripTime = Duration(minutes: json['time_to_reach_next'] ?? 0) as Duration?; var tripTime = Duration(minutes: json['time_to_reach_next'] ?? 0) as Duration?;
return Landmark( return Landmark(

View File

@ -29,6 +29,18 @@ class Trip with ChangeNotifier {
} }
} }
Future<int> landmarkPosition (Landmark landmark) async {
int i = 0;
for (Landmark l in landmarks) {
if (l.uuid == landmark.uuid) {
return i;
} else if (l.type != typeStart && l.type != typeFinish) {
i++;
}
}
return -1;
}
Trip({ Trip({
this.uuid = 'pending', this.uuid = 'pending',
@ -52,6 +64,7 @@ class Trip with ChangeNotifier {
totalTime = json['total_time']; totalTime = json['total_time'];
notifyListeners(); notifyListeners();
} }
void addLandmark(Landmark landmark) { void addLandmark(Landmark landmark) {
landmarks.add(landmark); landmarks.add(landmark);
notifyListeners(); notifyListeners();
@ -62,8 +75,16 @@ class Trip with ChangeNotifier {
notifyListeners(); notifyListeners();
} }
void removeLandmark(Landmark landmark) { void removeLandmark (Landmark landmark) async {
Landmark? previous = landmark.previous;
Landmark? next = landmark.next;
landmarks.remove(landmark); landmarks.remove(landmark);
// removing the landmark means we need to recompute the time between the two adjoined landmarks
if (previous != null && next != null) {
// previous.next = next happens automatically since we are using a LinkedList
previous.tripTime = null;
// TODO
}
notifyListeners(); notifyListeners();
} }
@ -72,6 +93,10 @@ class Trip with ChangeNotifier {
notifyListeners(); notifyListeners();
} }
void notifyUpdate(){
notifyListeners();
}
factory Trip.fromPrefs(SharedPreferences prefs, String uuid) { factory Trip.fromPrefs(SharedPreferences prefs, String uuid) {
String? content = prefs.getString('trip_$uuid'); String? content = prefs.getString('trip_$uuid');
Map<String, dynamic> json = jsonDecode(content!); Map<String, dynamic> json = jsonDecode(content!);
@ -80,7 +105,6 @@ class Trip with ChangeNotifier {
log('Loading trip $uuid with first landmark $firstUUID'); log('Loading trip $uuid with first landmark $firstUUID');
LinkedList<Landmark> landmarks = readLandmarks(prefs, firstUUID); LinkedList<Landmark> landmarks = readLandmarks(prefs, firstUUID);
trip.landmarks = landmarks; trip.landmarks = landmarks;
// notifyListeners();
return trip; return trip;
} }

View File

@ -1,33 +1,33 @@
import "dart:convert"; import "dart:convert";
import "dart:developer"; import "dart:developer";
import "package:anyway/utils/load_landmark_image.dart";
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:anyway/constants.dart'; import 'package:anyway/constants.dart';
import "package:anyway/utils/load_landmark_image.dart";
import "package:anyway/structs/landmark.dart"; import "package:anyway/structs/landmark.dart";
import "package:anyway/structs/trip.dart"; import "package:anyway/structs/trip.dart";
import "package:anyway/structs/preferences.dart"; import "package:anyway/structs/preferences.dart";
Dio dio = Dio( Dio dio = Dio(
BaseOptions( BaseOptions(
baseUrl: API_URL_BASE, baseUrl: API_URL_BASE,
connectTimeout: const Duration(seconds: 5), connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 120), receiveTimeout: const Duration(seconds: 120),
// also accept 500 errors, since we cannot rule out that the server is at fault. We still want to gracefully handle these errors // also accept 500 errors, since we cannot rule out that the server is at fault. We still want to gracefully handle these errors
validateStatus: (status) => status! <= 500, validateStatus: (status) => status! <= 500,
receiveDataWhenStatusError: true, receiveDataWhenStatusError: true,
// api is notoriously slow // api is notoriously slow
// headers: { // headers: {
// HttpHeaders.userAgentHeader: 'dio', // HttpHeaders.userAgentHeader: 'dio',
// 'api': '1.0.0', // 'api': '1.0.0',
// }, // },
contentType: Headers.jsonContentType, contentType: Headers.jsonContentType,
responseType: ResponseType.json, responseType: ResponseType.json,
), ),
); );
fetchTrip( fetchTrip(
Trip trip, Trip trip,
UserPreferences preferences, UserPreferences preferences,

View File

@ -1,11 +1,14 @@
import 'package:anyway/pages/current_trip.dart'; import 'package:anyway/main.dart';
import 'package:anyway/pages/onboarding.dart';
import 'package:anyway/structs/trip.dart';
import 'package:anyway/utils/load_trips.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:anyway/structs/trip.dart';
import 'package:anyway/utils/load_trips.dart';
import 'package:anyway/pages/current_trip.dart';
import 'package:anyway/pages/onboarding.dart';
Widget getFirstPage() { Widget getFirstPage() {
SavedTrips trips = SavedTrips(); SavedTrips trips = savedTrips;
trips.loadTrips(); trips.loadTrips();
return ListenableBuilder( return ListenableBuilder(
@ -15,7 +18,7 @@ Widget getFirstPage() {
if (items.isNotEmpty) { if (items.isNotEmpty) {
return TripPage(trip: items[0]); return TripPage(trip: items[0]);
} else { } else {
return OnboardingPage(); return const OnboardingPage();
} }
} }
); );