diff --git a/lib/services/api.dart b/lib/services/api.dart index e49d7bf..e48ae73 100644 --- a/lib/services/api.dart +++ b/lib/services/api.dart @@ -8,7 +8,7 @@ class Api { static const String _rootUrl = 'https://environment.data.gov.uk/flood-monitoring'; - static Future> fetchStations() async { + static Future> fetchAllStations() async { List stations = []; final response = await http.get(Uri.parse('$_rootUrl/id/stations')); if (response.statusCode == 200) { @@ -20,6 +20,23 @@ class Api { return stations; } + /// [limit] limits the number of entries that are requested from the API and [offset] returns the + /// list starting from the specified number + + static Future> fetchStationsByRange( + int limit, int offset) async { + List stations = []; + final response = await http + .get(Uri.parse('$_rootUrl/id/stations?_limit=$limit&_offset=$offset')); + if (response.statusCode == 200) { + final Map jsonStr = jsonDecode(response.body); + for (final str in jsonStr['items']) { + stations.add(FloodStation.fromMap(str)); + } + } + return stations; + } + static Future> fetchReadingsFromStation( String stationId) async { List readings = []; diff --git a/lib/services/flood_station_provider.dart b/lib/services/flood_station_provider.dart index 82202c8..a1f8a77 100644 --- a/lib/services/flood_station_provider.dart +++ b/lib/services/flood_station_provider.dart @@ -4,13 +4,31 @@ import '../model/flood_station.dart'; import 'api.dart'; class FloodStationProvider extends ChangeNotifier { - List _allStations = []; FloodStation? selectedStation; + List _allStations = []; + List get allStations => _allStations; + Future loadAllStationsInBatches({silent = false}) { + int offset = 0; + return Future.doWhile(() async { + final stations = await Api.fetchStationsByRange(500, offset); + if (stations.isNotEmpty) { + _allStations.addAll(stations); + if (!silent) { + notifyListeners(); + } + offset += 500; + return true; + } else { + return false; + } + }); + } + Future loadAllStations({silent = false}) { - return Api.fetchStations().then( + return Api.fetchAllStations().then( (value) { _allStations = value; if (!silent) {