RailwayStationsApiClient.dart (1783B)
1 import 'dart:convert'; 2 3 import 'package:flutter/foundation.dart'; 4 import 'package:grizzly_io/grizzly_io.dart'; 5 import 'package:http/http.dart' as http; 6 import 'package:meta/meta.dart'; 7 8 import '../models/models.dart'; 9 10 class RailwayStationsApiClient { 11 static const baseUrl = 'https://api.railway-stations.org'; 12 final http.Client httpClient; 13 14 RailwayStationsApiClient({ 15 @required this.httpClient, 16 }) : assert(httpClient != null); 17 18 Future<List<Country>> getCountries() async { 19 final countriesUrl = '$baseUrl/countries'; 20 final countriesResponse = await this.httpClient.get(countriesUrl); 21 if (countriesResponse.statusCode != 200) { 22 throw Exception('error getting countries'); 23 } 24 25 List<Country> countries = List(); 26 final countriesJson = jsonDecode(countriesResponse.body); 27 (countriesJson as List).forEach((element) { 28 countries.add(Country.fromJson(element)); 29 }); 30 return countries; 31 } 32 33 Future<List<Station>> getStations() async { 34 final stationsUrl = '$baseUrl/stations'; 35 final stationsResponse = await this.httpClient.get(stationsUrl); 36 if (stationsResponse.statusCode != 200) { 37 throw Exception('error getting stations'); 38 } 39 40 List<Station> stations = List(); 41 final stationsJson = jsonDecode(stationsResponse.body); 42 (stationsJson as List).forEach((element) { 43 stations.add(Station.fromJson(element)); 44 }); 45 return stations; 46 } 47 48 Future<List<List<String>>> getScores() async { 49 final scoresUrl = '$baseUrl/photographers.txt'; 50 final scoresResponse = await this.httpClient.get(scoresUrl); 51 if (scoresResponse.statusCode != 200) { 52 throw Exception('error getting stations'); 53 } 54 55 List<List<String>> scores = parseTsv(scoresResponse.body); 56 return scores; 57 } 58 }