diff --git a/lib/album_fetch.dart b/lib/album_fetch.dart index d26ceab..72ddd53 100644 --- a/lib/album_fetch.dart +++ b/lib/album_fetch.dart @@ -4,32 +4,31 @@ import 'dart:async'; import 'package:http/http.dart' as http; Future> fetchArrivals() async { - final response = await http - .get(Uri.parse('http://141.144.238.26:48502/arrivals/all')); + try { + final response = await http.get(Uri.parse('http://141.144.238.26:48502/arrivals/all')); - if (response.statusCode == 200) { - // If the server did return a 200 OK response, - // then parse the JSON. - List data = jsonDecode(response.body); - List posts = List.from(data.map((dynamic postJson) { - return Arrival.fromJson(postJson); - })); - } else { - // If the server did not return a 200 OK response, - // then throw an exception. - throw Exception('Failed to load Arrival'); + if (response.statusCode == 200) { + List data = jsonDecode(response.body); + List arrivals = List.from(data.map((dynamic arrivalJson) { + return Arrival.fromJson(arrivalJson); + })); + return arrivals; + } else { + throw Exception('Failed to load Arrival'); + } + } catch (error) { + throw Exception('Failed to fetch data: $error'); } - - throw Exception("API Unavailable"); } + class Arrival { final String timeOfDay; final int weekDay; final int tramLine; final bool direction; - const Arrival({ + Arrival({ required this.timeOfDay, required this.weekDay, required this.tramLine, @@ -37,21 +36,12 @@ class Arrival { }); factory Arrival.fromJson(Map json) { - return switch (json) { - { - 'time_of_day': String jsonTime, - 'week_day': int jsonDay, - 'tram_line': int jsonTramLine, - 'direction': bool jsonDirec, - } => - Arrival( - // Class : json declaration - timeOfDay: jsonTime, - weekDay: jsonDay, - tramLine: jsonTramLine, - direction: jsonDirec, - ), - _ => throw const FormatException('Failed to load Arrival.'), - }; + return Arrival( + timeOfDay: json['time_of_day'] as String, + weekDay: json['week_day'] as int, + tramLine: json['tram_line'] as int, + direction: json['direction'] as bool, + ); } } +