From 70895a74c52a63cb51709569540595020f3fb7eb Mon Sep 17 00:00:00 2001 From: Supermjork Date: Tue, 26 Dec 2023 19:23:43 +0200 Subject: [PATCH] Fetching but Type Conversion Err --- lib/album_fetch.dart | 53 +++++++++++++++++++++++++++++ lib/{albut.dart => album_post.dart} | 0 lib/fetcher.dart | 28 ++++++++++++++- 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 lib/album_fetch.dart rename lib/{albut.dart => album_post.dart} (100%) diff --git a/lib/album_fetch.dart b/lib/album_fetch.dart new file mode 100644 index 0000000..658c896 --- /dev/null +++ b/lib/album_fetch.dart @@ -0,0 +1,53 @@ + +import 'dart:convert'; +import 'dart:async'; + +import 'package:http/http.dart' as http; + +Future fetchArrivals() async { + final response = await http + .get(Uri.parse(DB_URL)); + + if (response.statusCode == 200) { + // If the server did return a 200 OK response, + // then parse the JSON. + return FetchAlbum.fromJson(jsonDecode(response.body) as Map); + } else { + // If the server did not return a 200 OK response, + // then throw an exception. + throw Exception('Failed to load album'); + } +} + +class FetchAlbum { + final String timeOfDay; + final int weekDay; + final String tramLine; + final bool direction; + + const FetchAlbum({ + required this.timeOfDay, + required this.weekDay, + required this.tramLine, + required this.direction, + }); + + factory FetchAlbum.fromJson(Map json) { + return switch (json) { + { + 'time_of_day': String jsonTime, + 'week_day': int jsonDay, + 'tram_line': String jsonTramLine, + 'direction': bool jsonDirec, + } => + FetchAlbum( + // Class : json declaration + timeOfDay: jsonTime, + weekDay: jsonDay, + tramLine: jsonTramLine, + direction: jsonDirec, + ), + _ => throw const FormatException('Failed to load album.'), + }; + } +} diff --git a/lib/albut.dart b/lib/album_post.dart similarity index 100% rename from lib/albut.dart rename to lib/album_post.dart diff --git a/lib/fetcher.dart b/lib/fetcher.dart index eb5894b..9238d39 100644 --- a/lib/fetcher.dart +++ b/lib/fetcher.dart @@ -1,8 +1,22 @@ import 'package:flutter/material.dart'; +import 'package:witl/album_fetch.dart'; -class FetchAPI extends StatelessWidget { +class FetchAPI extends StatefulWidget { const FetchAPI({super.key}); + @override + State createState() => _FetchAPIState(); +} + +class _FetchAPIState extends State { + late Future fetchedAlbum; + + @override + void initState() { + super.initState(); + fetchedAlbum = fetchArrivals(); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -11,6 +25,18 @@ class FetchAPI extends StatelessWidget { ), body: ListView( children: [ + FutureBuilder ( + future: fetchedAlbum, + builder: (context, snapshot) { + if (snapshot.hasData) { + return Text(snapshot.data!.timeOfDay); + } else if (snapshot.hasError) { + return Text('${snapshot.error}'); + } + + return const CircularProgressIndicator(); + }, + ), InkWell( onTap: () { Navigator.pushNamedAndRemoveUntil(