Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 73 ยท Projects

Project: Weather App

Build a Flutter weather app: an API client, sealed loading and error states, debounced city search, a small cache and friendly error UI.

A weather app is the standard project for networking. It forces you to deal with everything that makes real apps hard: a slow server, a missing network, a city that does not exist, a user who types faster than requests finish, and the wish not to download the same data twice. In this project you build the data layer and the UI states, and every important piece has a runnable stand-in.

It combines HTTP Requests and JSON, FutureBuilder, StreamBuilder and Async UI, Futures and Streams and sealed classes from Collections and Generics.

Real vs stand-in. The Dart is real and read-only here. It uses the free Open-Meteo forecast API as the example server (no key needed), but check its current docs before you ship. The live examples are JavaScript stand-ins with a fake API that has delays and failures, so they are deterministic and never touch a real network.

Every screen state

Idle Nothing searched yet.
Loading Spinner while waiting.
Data Show the forecast.
Error Message and a retry button.
1 / 2

Step 1: model the data and the states

Keep the model to what the screen shows:

DART
class Weather {
  const Weather({required this.city, required this.temperatureC, required this.windKmh, required this.code});

  final String city;
  final double temperatureC;
  final double windKmh;
  final int code;                         // WMO weather code

  factory Weather.fromJson(String city, Map<String, dynamic> json) {
    final current = json['current'] as Map<String, dynamic>;
    return Weather(
      city: city,
      temperatureC: (current['temperature_2m'] as num).toDouble(),
      windKmh: (current['wind_speed_10m'] as num).toDouble(),
      code: current['weather_code'] as int,
    );
  }
}

The screen can be in exactly four situations. A sealed class lists them, and a switch forces you to handle every one:

DART
sealed class WeatherState { const WeatherState(); }
class Idle extends WeatherState { const Idle(); }
class Loading extends WeatherState { const Loading(); }
class Loaded extends WeatherState { const Loaded(this.weather); final Weather weather; }
class Failed extends WeatherState { const Failed(this.message); final String message; }

This beats a pile of booleans (isLoading, hasError, data) which can contradict each other, such as "loading and error at once".

Step 2: the API client

The client turns a city name into coordinates (geocoding), then asks for the forecast. Errors become your own exception type so the UI never sees raw HTTP details:

DART
class WeatherException implements Exception {
  const WeatherException(this.message);
  final String message;
}

class WeatherApi {
  WeatherApi(this._client);
  final http.Client _client;

  Future<Weather> fetch(String city) async {
    try {
      final geo = await _client
          .get(Uri.https('geocoding-api.open-meteo.com', '/v1/search', {'name': city, 'count': '1'}))
          .timeout(const Duration(seconds: 8));
      if (geo.statusCode != 200) throw const WeatherException('Search service is unavailable.');

      final results = (jsonDecode(geo.body) as Map<String, dynamic>)['results'] as List<dynamic>?;
      if (results == null || results.isEmpty) throw WeatherException('No city called "$city".');
      final place = results.first as Map<String, dynamic>;

      final forecast = await _client
          .get(Uri.https('api.open-meteo.com', '/v1/forecast', {
            'latitude': '${place['latitude']}',
            'longitude': '${place['longitude']}',
            'current': 'temperature_2m,wind_speed_10m,weather_code',
          }))
          .timeout(const Duration(seconds: 8));
      if (forecast.statusCode != 200) throw const WeatherException('Forecast is unavailable.');

      return Weather.fromJson(place['name'] as String, jsonDecode(forecast.body) as Map<String, dynamic>);
    } on TimeoutException {
      throw const WeatherException('The server took too long. Try again.');
    } on SocketException {
      throw const WeatherException('No internet connection.');
    }
  }
}

Always set a timeout; without one a stalled connection leaves the spinner on forever. Catch low-level exceptions and translate them into messages a person can act on.

Step 3: a cache in the repository

If the user checks the same city twice in a minute, the second answer can come from memory. A repository wraps the client and remembers answers for a short time (a TTL, time to live):

DART
class WeatherRepository {
  WeatherRepository(this._api, {this.ttl = const Duration(minutes: 10), DateTime Function()? now})
      : _now = now ?? DateTime.now;

  final WeatherApi _api;
  final Duration ttl;
  final DateTime Function() _now;
  final Map<String, ({Weather weather, DateTime at})> _cache = {};

  Future<Weather> forCity(String city, {bool forceRefresh = false}) async {
    final key = city.trim().toLowerCase();
    final hit = _cache[key];
    if (!forceRefresh && hit != null && _now().difference(hit.at) < ttl) return hit.weather;
    final weather = await _api.fetch(city.trim());
    _cache[key] = (weather: weather, at: _now());
    return weather;
  }
}

Passing the clock in (now) is a testing trick: a test can move time forward without waiting ten minutes. Normalizing the key (trim, lower case) makes "Paris" and " paris " the same entry.

Stand-in: states, API and cache

Here is the same design in JavaScript with a fake API. Each call logs when it "hits the server", so you can see the cache working. The clock is a variable we move by hand.

JS Repository with a TTL cache and error states

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 4: state and search with debounce

The controller owns a WeatherState. A user typing "L-o-n-d-o-n" should not fire six requests, so wait until typing pauses (debounce), and ignore answers that arrive for an outdated search:

DART
class WeatherController extends ChangeNotifier {
  WeatherController(this._repository);
  final WeatherRepository _repository;

  WeatherState state = const Idle();
  Timer? _debounce;
  int _searchId = 0;

  void onQueryChanged(String text) {
    _debounce?.cancel();
    if (text.trim().length < 2) {
      state = const Idle();
      notifyListeners();
      return;
    }
    _debounce = Timer(const Duration(milliseconds: 400), () => search(text));
  }

  Future<void> search(String city, {bool forceRefresh = false}) async {
    final id = ++_searchId;                 // remember which search this is
    state = const Loading();
    notifyListeners();
    try {
      final weather = await _repository.forCity(city, forceRefresh: forceRefresh);
      if (id != _searchId) return;          // a newer search started: drop this answer
      state = Loaded(weather);
    } on WeatherException catch (e) {
      if (id != _searchId) return;
      state = Failed(e.message);
    }
    notifyListeners();
  }

  @override
  void dispose() {
    _debounce?.cancel();
    super.dispose();
  }
}

The _searchId check prevents a classic bug: a slow answer for "Lon" arriving after the answer for "London" and overwriting it.

Step 5: the screen draws every state

DART
Widget buildBody(WeatherState state, VoidCallback onRetry) {
  return switch (state) {
    Idle() => const Center(child: Text('Type a city name')),
    Loading() => const Center(child: CircularProgressIndicator()),
    Loaded(:final weather) => Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(weather.city, style: const TextStyle(fontSize: 28)),
          Text('${weather.temperatureC.round()}ยฐC', style: const TextStyle(fontSize: 64)),
          Text('Wind ${weather.windKmh.round()} km/h'),
        ],
      ),
    Failed(:final message) => Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.cloud_off, size: 48),
            Text(message),
            const SizedBox(height: 12),
            FilledButton(onPressed: onRetry, child: const Text('Try again')),
          ],
        ),
      ),
  };
}

Because WeatherState is sealed, deleting the Failed branch is a compile error. Good error UI says what happened in plain words and offers one clear next step.

Stand-in: debounce and stale answers

Time is simulated with a list of keystrokes at fixed moments, so the output is always the same.

JS Debounce and dropping outdated answers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ideas to extend it

  • Save the last searched city with shared preferences (see Local Storage).
  • Pull to refresh with forceRefresh: true.
  • A seven-day forecast list and weather icons from the code.
  • Use connectivity_plus to show an offline banner.
  • Test the repository with a fake client and a fake clock.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a sealed class for the screen state instead of several booleans?

    A sealed hierarchy lists every state, so impossible mixes like loading plus error cannot happen and missing cases fail at compile time.
  2. 2. What does debouncing a search field do?

    Each keystroke restarts a short timer; the search runs only when the timer finishes.
  3. 3. Why compare a search id before showing a result?

    A slow request for old text must not overwrite the result of the newest search.
  4. 4. What is a cache TTL?

    After the time to live passes, the repository asks the server again.

Summary

  • Model the screen as a sealed state: idle, loading, loaded, failed.
  • Put HTTP and JSON in a client, translate errors into your own exceptions, and always set a timeout.
  • A repository can add a TTL cache; inject the clock so tests control time.
  • Debounce typing and ignore outdated answers with a search id.
  • Error UI should explain in plain words and offer a retry.

Next: Project: Realtime Chat App