Learn/Mini Projects/Project: Weather App

Project: Weather App

Build a weather app with API integration

15 min~6 min read+100 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Weather Display Widget
  2. 2. API Reliability Strategy
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. Quick Glossary
  10. 10. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Weather App Project

This project teaches you how to work with real APIs and display live data in a beautiful layout. You will build a weather application that fetches current weather conditions from the OpenWeatherMap API, displays temperature, humidity, and wind speed, handles loading and error states gracefully, and lets users search for any city. This covers HTTP requests, JSON parsing, model classes, FutureBuilder, error handling, and polished UI design all in one project.

Features to build:

  • Fetch live weather data from OpenWeatherMap API
  • Display current temperature, condition, humidity, and wind speed
  • Show weather icons from the API
  • Search for weather by city name
  • Handle loading spinner and error messages with retry
dart
1// Weather model
2class Weather {
3 final String city;
4 final double temperature;
5 final String condition;
6 final String icon;
7 final double humidity;
8 final double windSpeed;
9
10 Weather({
11 required this.city,
12 required this.temperature,
13 required this.condition,
14 required this.icon,
15 required this.humidity,
16 required this.windSpeed,
17 });
18
19 factory Weather.fromJson(Map<String, dynamic> json) {
20 return Weather(
21 city: json['name'],
22 temperature: json['main']['temp'].toDouble(),
23 condition: json['weather'][0]['main'],
24 icon: json['weather'][0]['icon'],
25 humidity: json['main']['humidity'].toDouble(),
26 windSpeed: json['wind']['speed'].toDouble(),
27 );
28 }
29}
30
31// Weather service
32class WeatherService {
33 static const apiKey = 'YOUR_API_KEY';
34 static const baseUrl = 'https://api.openweathermap.org/data/2.5';
35
36 Future<Weather> getWeather(String city) async {
37 final url = '$baseUrl/weather?q=$city&appid=$apiKey&units=metric';
38 final response = await http.get(Uri.parse(url));
39
40 if (response.statusCode == 200) {
41 return Weather.fromJson(jsonDecode(response.body));
42 } else {
43 throw Exception('Failed to load weather');
44 }
45 }
46}

Weather Display Widget

The WeatherCard widget takes a Weather model and displays it in a clean card layout. The city name goes at the top, followed by the weather icon from the API alongside a large temperature reading. Below that, a row of secondary info shows humidity and wind speed. This kind of structured layout makes the data easy to read at a glance.

dart
1class WeatherCard extends StatelessWidget {
2 final Weather weather;
3
4 const WeatherCard({required this.weather});
5
6 @override
7 Widget build(BuildContext context) {
8 return Card(
9 margin: EdgeInsets.all(16),
10 child: Padding(
11 padding: EdgeInsets.all(24),
12 child: Column(
13 children: [
14 Text(
15 weather.city,
16 style: Theme.of(context).textTheme.headlineMedium,
17 ),
18 SizedBox(height: 16),
19 Row(
20 mainAxisAlignment: MainAxisAlignment.center,
21 children: [
22 Image.network(
23 'https://openweathermap.org/img/wn/${weather.icon}@2x.png',
24 width: 80,
25 ),
26 Text(
27 '${weather.temperature.round()}°C',
28 style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
29 ),
30 ],
31 ),
32 Text(weather.condition, style: TextStyle(fontSize: 20)),
33 SizedBox(height: 24),
34 Row(
35 mainAxisAlignment: MainAxisAlignment.spaceAround,
36 children: [
37 _buildInfoItem(Icons.water_drop, '${weather.humidity}%', 'Humidity'),
38 _buildInfoItem(Icons.air, '${weather.windSpeed} m/s', 'Wind'),
39 ],
40 ),
41 ],
42 ),
43 ),
44 );
45 }
46}

API Reliability Strategy

Real weather apps fail more often from network and API issues than UI bugs. Build a reliability plan first:

  • Keep all HTTP logic in WeatherService so UI widgets stay simple.
  • Map status codes to user-friendly messages (401 invalid key, 404 city not found, 429 rate limit).
  • Add request timeout handling and a clear retry path.
  • Debounce search input so typing "London" does not trigger six API calls.
  • Cache the last successful response per city for quick back navigation.

When reliability is explicit in your architecture, your app feels professional even when the network is unstable.

Weather Failure States To Handle

  • User submits an empty city name or only spaces.
  • Device is offline or DNS lookup fails.
  • API returns 404 because city name is invalid or misspelled.
  • API key is missing, revoked, or exceeds quota limits.
  • Slow response arrives after user already searched for another city.

Weather App QA Checklist

  • FutureBuilder states are complete: loading, success, empty, and error all render intentionally.
  • Retry action works and does not duplicate requests uncontrollably.
  • Weather icon URL failures fall back to a placeholder UI.
  • Temperature, humidity, and wind values are formatted consistently and read clearly.
  • API key is not hardcoded in public source for production builds.

This Lesson In Simple Words

Build a weather app with API integration. Networking lessons teach your app how to request, store, and display remote data safely.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Always model loading, success, empty, and error states before hooking the UI.

Deep Understanding Guide

Why this lesson matters

Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Treat every network call as unreliable and design graceful fallback behavior.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Triggering API calls inside build methods and causing duplicate requests.
  • Assuming response fields always exist without null checks or parsing safeguards.
  • Displaying backend errors directly to users without safe messaging.
  • Skipping retry and offline handling for key user actions.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Implement one repository with timeout, retry, and typed parsing.
  • Add pull-to-refresh and compare stale vs fresh data behavior.
  • Create a clear UI state for empty list and network failure cases.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What builder widget is best for loading weather data?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • future: A single asynchronous result delivered later.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Repository and service boundaries keep networking logic testable and replaceable.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Project: Weather App" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Triggering API calls inside build methods and causing duplicate requests.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What builder widget is best for loading weather data?

FutureBuilder handles the async API call and different states (loading, error, data).

What package is commonly used for HTTP requests in Flutter?

The http package (or dio for advanced features) is the standard way to make HTTP requests in Flutter.

How do you parse JSON from an API response?

jsonDecode from dart:convert parses a JSON string into a Dart Map or List.

What should you check before using API response data?

Always check response.statusCode == 200 before parsing data. Handle errors for other status codes.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue