Enhance navigation and error handling; implement global navigator and messenger keys, update schedule progress retrieval, and improve error messaging in various services

This commit is contained in:
Sven laptop
2026-05-17 22:29:41 +02:00
parent 0e10757c49
commit 73de0d713e
11 changed files with 430 additions and 63 deletions
+3
View File
@@ -3,6 +3,7 @@ import 'screens/login_screen.dart';
import 'screens/schedule_overview_screen.dart';
import 'services/auth_service.dart';
import 'theme/app_theme.dart';
import 'services/app_navigator.dart';
void main() {
runApp(const MainApp());
@@ -15,6 +16,8 @@ class MainApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bus Terminal',
navigatorKey: navigatorKey,
scaffoldMessengerKey: messengerKey,
theme: AppTheme.lightTheme(),
darkTheme: AppTheme.darkTheme(),
themeMode: ThemeMode.system,
+2 -1
View File
@@ -19,7 +19,8 @@ class User {
} else if (rawUserCode is String) {
parsedUserCode = int.tryParse(rawUserCode) ?? (throw FormatException('Invalid userCode'));
} else {
throw FormatException('Missing userCode');
// If the backend doesn't return a userCode, treat as unknown (-1)
parsedUserCode = -1;
}
return User(
@@ -27,7 +27,7 @@ class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with Ti
void initState() {
super.initState();
_scheduleFuture = _scheduleService.getSchedules(_selectedDate);
_tabController = TabController(length: 2, vsync: this);
_tabController = TabController(length: 3, vsync: this);
}
@override
@@ -120,12 +120,16 @@ class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with Ti
],
),
const SizedBox(height: 20),
SizedBox(
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: () async {
onPressed: () async {
try {
await _scheduleService.updateScheduleStatus(svc.id, 'in_progress');
await _scheduleService.updateScheduleStatus(
svc.id,
'in_progress',
date: svc.startTime,
);
if (!mounted) return;
Navigator.of(sheetContext).pop();
@@ -157,11 +161,18 @@ class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with Ti
))
.toList();
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => NavigationScreen(route: routeObj, initialStops: navStops),
),
);
try {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => NavigationScreen(route: routeObj, initialStops: navStops),
),
);
} catch (navErr) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Navigatiefout: ${navErr.toString()}')),
);
}
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
@@ -227,6 +238,7 @@ class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with Ti
tabs: const [
Tab(icon: Icon(Icons.calendar_today), text: 'Dagschema'),
Tab(icon: Icon(Icons.repeat), text: 'Vaste diensten'),
Tab(icon: Icon(Icons.timeline), text: 'Voortgang'),
],
),
actions: [
@@ -249,12 +261,131 @@ class _ScheduleOverviewScreenState extends State<ScheduleOverviewScreen> with Ti
scheduleFuture: _scheduleFuture,
),
const RecurringSchedulesScreen(),
_ProgressTab(
scheduleService: _scheduleService,
selectedDate: _selectedDate,
scheduleFuture: _scheduleFuture,
),
],
),
);
}
}
class _ProgressTab extends StatelessWidget {
final ScheduleService scheduleService;
final DateTime selectedDate;
final Future<List<sched.ServiceSchedule>> scheduleFuture;
const _ProgressTab({
required this.scheduleService,
required this.selectedDate,
required this.scheduleFuture,
});
@override
Widget build(BuildContext context) {
final dateStr = '${selectedDate.year}-${selectedDate.month.toString().padLeft(2, '0')}-${selectedDate.day.toString().padLeft(2, '0')}';
return Column(
children: [
Container(
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Voortgang voor $dateStr', style: Theme.of(context).textTheme.titleLarge),
IconButton(
onPressed: () async {
// refresh handled by parent via reselecting date; show a simple feedback
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Ververs de datum in Dagschema-tab om andere datum te laden')));
},
icon: const Icon(Icons.info_outline),
),
],
),
),
Expanded(
child: FutureBuilder<List<sched.ServiceSchedule>>(
future: scheduleFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) return const Center(child: CircularProgressIndicator());
if (snapshot.hasError) return Center(child: Text('Fout bij laden: ${snapshot.error}'));
final schedules = snapshot.data ?? [];
if (schedules.isEmpty) return Center(child: Text('Geen diensten op $dateStr'));
return ListView.builder(
padding: const EdgeInsets.all(12),
itemCount: schedules.length,
itemBuilder: (context, index) {
final svc = schedules[index];
return Card(
child: ListTile(
title: Text('Lijn ${svc.lineNumber} — ${svc.busName}'),
subtitle: Text('${_formatTime(svc.startTime)}'),
trailing: TextButton(
onPressed: () async {
try {
final progress = await scheduleService.getScheduleProgress(svc.id, selectedDate);
if (!context.mounted) return;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (ctx) {
final stops = (progress['stops'] as List<dynamic>?) ?? [];
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Voortgang — Lijn ${svc.lineNumber}', style: Theme.of(ctx).textTheme.headlineSmall),
const SizedBox(height: 8),
Text('Status: ${progress['schedule']?['status'] ?? 'onbekend'}'),
Text('Driver state: ${progress['driverState'] ?? 'onbekend'}'),
Text('Passed: ${progress['passedStopCount'] ?? 0} / ${progress['totalStopCount'] ?? 0}'),
const SizedBox(height: 12),
const Text('Haltes:'),
const SizedBox(height: 8),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: stops.length,
itemBuilder: (c, i) {
final s = stops[i] as Map<String, dynamic>;
return ListTile(
dense: true,
title: Text('${s['stopOrder']}. ${s['stopName']}'),
subtitle: Text('Scheduled: ${s['scheduledPassedAt'] ?? '-'}\nActual: ${s['actualPassedAt'] ?? '-'}'),
);
},
),
),
],
),
);
},
);
} catch (e) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Kon voortgang niet laden: $e')));
}
},
child: const Text('Bekijk voortgang'),
),
),
);
},
);
},
),
),
],
);
}
}
class _DailyScheduleTab extends StatelessWidget {
final ScheduleService scheduleService;
final DateTime selectedDate;
@@ -0,0 +1,29 @@
import 'package:flutter/material.dart';
import 'auth_service.dart';
/// Global navigator and messenger keys so services can navigate/logout
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final GlobalKey<ScaffoldMessengerState> messengerKey = GlobalKey<ScaffoldMessengerState>();
/// Handle expired authentication: clear stored token and navigate to login.
Future<void> handleAuthExpired({String? message}) async {
try {
await AuthService().logout();
} catch (_) {}
// Show a message if possible
try {
final messenger = messengerKey.currentState;
if (messenger != null && message != null) {
messenger.showSnackBar(SnackBar(content: Text(message)));
}
} catch (_) {}
// Navigate to login, removing all previous routes
try {
final nav = navigatorKey.currentState;
if (nav != null) {
nav.pushNamedAndRemoveUntil('/login', (r) => false);
}
} catch (_) {}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import '../models/user.dart';
/// Authentication Service
class AuthService {
static const String _apiBaseUrl = 'http://192.168.2.66:5000';
static const String _apiBaseUrl = 'http://api.transit.local:5000';
static const String _tokenKey = 'auth_token';
late SharedPreferences _prefs;
+10 -3
View File
@@ -1,9 +1,16 @@
/// Custom exception for authentication errors
import 'app_navigator.dart';
class UnauthorizedException implements Exception {
final String message;
UnauthorizedException(this.message);
UnauthorizedException(this.message) {
// Trigger centralized logout/navigation asynchronously
try {
handleAuthExpired(message: message);
} catch (_) {}
}
@override
String toString() => message;
}
@@ -85,7 +85,7 @@ class NavigationService {
throw Exception('Failed to get route (400) and fallback failed: ${e.toString()}');
}
} else {
throw Exception('Failed to get route: ${response.statusCode}');
throw Exception('Failed to get route: ${response.statusCode} -- response body: ${response.body}');
}
} catch (e) {
throw Exception('Navigation error: $e');
@@ -110,7 +110,25 @@ class NavigationService {
final response = await http.get(Uri.parse(url));
if (response.statusCode != 200) {
throw Exception('Failed to get route: ${response.statusCode}');
if (response.statusCode == 400) {
final distanceMeters = _sumDistancesBetween(stops);
final durationSec = (distanceMeters / 11.111111).toInt();
final leg = RouteLeg.fromPoints(
points: stops,
distance: distanceMeters,
duration: durationSec,
summary: 'Direct fallback',
);
return NavigationRoute(
start: stops.first,
end: stops.last,
legs: [leg],
totalDistance: distanceMeters,
totalDuration: durationSec,
);
}
throw Exception('Failed to get route: ${response.statusCode} -- response body: ${response.body}');
}
final data = jsonDecode(response.body) as Map<String, dynamic>?;
@@ -165,7 +183,7 @@ class NavigationService {
final route = NavigationRoute(start: stops.first, end: stops.last, legs: [leg], totalDistance: distanceMeters, totalDuration: durationSec);
return OptimizedRouteResult(route: route, orderedStops: stops);
}
throw Exception('Failed to get optimized route: ${response.statusCode}');
throw Exception('Failed to get optimized route: ${response.statusCode} -- response body: ${response.body}');
}
final data = jsonDecode(response.body) as Map<String, dynamic>?;
@@ -287,7 +305,7 @@ class NavigationService {
final leg = RouteLeg.fromPoints(points: [start, end], distance: distanceMeters, duration: durationSec, summary: 'Direct');
return [NavigationRoute(start: start, end: end, legs: [leg], totalDistance: distanceMeters, totalDuration: durationSec)];
} else {
throw Exception('Failed to get routes: ${response.statusCode}');
throw Exception('Failed to get routes: ${response.statusCode} -- response body: ${response.body}');
}
} catch (e) {
throw Exception('Navigation error: $e');
+47 -30
View File
@@ -7,9 +7,7 @@ import 'exceptions.dart';
/// Schedule/Route Service
class ScheduleService {
// TODO: Implement API connector - configure base URL from env/config
// Transit API runs on port 5001
static const String _apiBaseUrl = 'http://192.168.2.66:5001';
static const String _apiBaseUrl = 'https://transit.xtransit.testinstance.nl';
final _authService = AuthService();
/// Get public schedule overview for a specific date.
@@ -141,12 +139,28 @@ class ScheduleService {
return getDailySchedule(DateTime.now());
}
/// Get per-date progress for a schedule occurrence (public endpoint)
Future<Map<String, dynamic>> getScheduleProgress(int scheduleId, DateTime date) async {
try {
final dateStr = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
final uri = Uri.parse('$_apiBaseUrl/public/schedules/$scheduleId/progress').replace(queryParameters: {'date': dateStr});
final response = await http.get(uri);
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
}
throw Exception('Failed to load progress: ${response.statusCode}');
} catch (e) {
throw Exception('Schedule progress error: $e');
}
}
/// Get route details
Future<Route> getRouteDetails(int routeId) async {
try {
final headers = await _authService.getAuthHeaders();
// Transit API exposes route details at /routes/:routeId
final response = await http.get(
Uri.parse('$_apiBaseUrl/routes/$routeId'),
headers: headers,
@@ -156,10 +170,10 @@ class ScheduleService {
final data = jsonDecode(response.body) as Map<String, dynamic>;
return Route.fromJson(data);
} else if (response.statusCode == 401 || response.statusCode == 403) {
await _authService.logout();
throw UnauthorizedException('Session expired - Please login again');
} else {
throw Exception('Failed to load route: ${response.statusCode}');
final body = response.body;
throw Exception('Failed to load route: ${response.statusCode} -- response body: $body');
}
} catch (e) {
if (e is UnauthorizedException) rethrow;
@@ -180,7 +194,6 @@ class ScheduleService {
);
if (response.statusCode == 401 || response.statusCode == 403) {
await _authService.logout();
throw UnauthorizedException('Session expired - Please login again');
} else if (response.statusCode != 200) {
throw Exception('Failed to update status: ${response.statusCode}');
@@ -192,18 +205,23 @@ class ScheduleService {
}
/// Update schedule status for driver-facing schedule workflows.
Future<void> updateScheduleStatus(int scheduleId, String status) async {
Future<void> updateScheduleStatus(int scheduleId, String status, {DateTime? date}) async {
try {
final headers = await _authService.getAuthHeaders();
final body = <String, dynamic>{'status': status};
if (date != null) {
final dateStr = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
body['date'] = dateStr;
}
final response = await http.patch(
Uri.parse('$_apiBaseUrl/driver/schedules/$scheduleId/status'),
headers: headers,
body: jsonEncode({'status': status}),
body: jsonEncode(body),
);
if (response.statusCode == 401 || response.statusCode == 403) {
await _authService.logout();
throw UnauthorizedException('Session expired - Please login again');
} else if (response.statusCode != 200) {
throw Exception('Failed to update schedule status: ${response.statusCode}');
@@ -226,27 +244,25 @@ class ScheduleService {
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
final stops = (data['stops'] as List?)
?.map((s) => s as Map<String, dynamic>)
.map((s) {
final lat = (s['latitude'] ?? s['lat']) as num?;
final lon = (s['longitude'] ?? s['lon']) as num?;
final name = (s['name'] ?? s['stop_name'] ?? s['stopName']) as String?;
if (lat == null || lon == null) return null;
return NavigationPoint(
latitude: lat.toDouble(),
longitude: lon.toDouble(),
name: name,
);
})
.whereType<NavigationPoint>()
.toList() ?? [];
final raw = data['stops'] as List? ?? [];
final stops = raw.map((s) => s as Map<String, dynamic>).map((s) {
final lat = (s['latitude'] ?? s['lat']) as num?;
final lon = (s['longitude'] ?? s['lon']) as num?;
final name = (s['name'] ?? s['stop_name'] ?? s['stopName']) as String?;
if (lat == null || lon == null) return null;
return NavigationPoint(
latitude: lat.toDouble(),
longitude: lon.toDouble(),
name: name,
);
}).whereType<NavigationPoint>().toList();
return stops;
} else if (response.statusCode == 401 || response.statusCode == 403) {
await _authService.logout();
throw UnauthorizedException('Session expired - Please login again');
} else {
throw Exception('Failed to load stops: ${response.statusCode}');
final body = response.body;
throw Exception('Failed to load stops: ${response.statusCode} -- response body: $body');
}
} catch (e) {
if (e is UnauthorizedException) rethrow;
@@ -263,12 +279,13 @@ class ScheduleService {
try {
final headers = await _authService.getAuthHeaders();
final body = <String, dynamic>{};
if (actualPassedAt != null) body['actualPassedAt'] = actualPassedAt.toIso8601String();
final response = await http.post(
Uri.parse('$_apiBaseUrl/driver/schedules/$scheduleId/stops/$stopOrder/passed'),
headers: headers,
body: jsonEncode({
if (actualPassedAt != null) 'actualPassedAt': actualPassedAt.toIso8601String(),
}),
body: jsonEncode(body),
);
if (response.statusCode == 401 || response.statusCode == 403) {
+12 -5
View File
@@ -67,11 +67,18 @@ class RouteCard extends StatelessWidget {
// Ignore status update errors here; navigation should still open.
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => NavigationScreen(route: route),
),
);
try {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => NavigationScreen(route: route),
),
);
} catch (e) {
// Surface navigation errors to the user so they can report/log.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Navigatiefout: ${e.toString()}')),
);
}
},
borderRadius: BorderRadius.circular(20),
splashFactory: InkSparkle.splashFactory,