Project: Weather App with a REST API

Google Flutter 16 min min read Updated: Nov 16, 2026 Intermediate
Project: Weather App with a REST API
Intermediate Topic 2 of 4

What We Build

A weather app where the user types a city and sees the current temperature, wind and a 5 day forecast. We use the Open-Meteo API because it is free and needs no API key.

API details can change: The URLs and field names below follow the public Open-Meteo documentation at open-meteo.com. If a field name differs when you run the app, check their docs and adjust.

Step 1: Setup

bash flutter create weather_app cd weather_app flutter pub add http

Remember the INTERNET permission in AndroidManifest.xml for release builds.

Step 2: The Endpoints

text Find a city: https://geocoding-api.open-meteo.com/v1/search?name=Pune&count=1 Get the weather: https://api.open-meteo.com/v1/forecast?latitude=18.52&longitude=73.85 &current=temperature_2m,wind_speed_10m,weather_code &daily=temperature_2m_max,temperature_2m_min,weather_code &timezone=auto

Step 3: Models

dart // lib/models/weather.dart class City { final String name; final String country; final double latitude; final double longitude; const City({required this.name, required this.country, required this.latitude, required this.longitude}); factory City.fromJson(Map<String, dynamic> json) => City( name: json['name'] as String, country: (json['country'] as String?) ?? '', latitude: (json['latitude'] as num).toDouble(), longitude: (json['longitude'] as num).toDouble(), ); } class DayForecast { final DateTime date; final double max; final double min; final int code; const DayForecast({required this.date, required this.max, required this.min, required this.code}); } class Weather { final double temperature; final double windSpeed; final int code; final List<DayForecast> days; const Weather({required this.temperature, required this.windSpeed, required this.code, required this.days}); factory Weather.fromJson(Map<String, dynamic> json) { final current = json['current'] as Map<String, dynamic>; final daily = json['daily'] as Map<String, dynamic>; final dates = (daily['time'] as List).cast<String>(); final maxes = daily['temperature_2m_max'] as List; final mins = daily['temperature_2m_min'] as List; final codes = daily['weather_code'] as List; return Weather( temperature: (current['temperature_2m'] as num).toDouble(), windSpeed: (current['wind_speed_10m'] as num).toDouble(), code: current['weather_code'] as int, days: [ for (var i = 0; i < dates.length; i++) DayForecast( date: DateTime.parse(dates[i]), max: (maxes[i] as num).toDouble(), min: (mins[i] as num).toDouble(), code: codes[i] as int, ), ], ); } }

Step 4: The Service

dart // lib/services/weather_service.dart import 'dart:convert'; import 'package:http/http.dart' as http; import '../models/weather.dart'; class WeatherService { Future<City> findCity(String name) async { final uri = Uri.https('geocoding-api.open-meteo.com', '/v1/search', { 'name': name, 'count': '1', }); final response = await http.get(uri).timeout(const Duration(seconds: 10)); if (response.statusCode != 200) throw Exception('City search failed'); final data = jsonDecode(response.body) as Map<String, dynamic>; final results = data['results'] as List<dynamic>?; if (results == null || results.isEmpty) throw Exception('City "$name" not found'); return City.fromJson(results.first as Map<String, dynamic>); } Future<Weather> getWeather(City city) async { final uri = Uri.https('api.open-meteo.com', '/v1/forecast', { 'latitude': '${city.latitude}', 'longitude': '${city.longitude}', 'current': 'temperature_2m,wind_speed_10m,weather_code', 'daily': 'temperature_2m_max,temperature_2m_min,weather_code', 'timezone': 'auto', }); final response = await http.get(uri).timeout(const Duration(seconds: 10)); if (response.statusCode != 200) throw Exception('Weather request failed'); return Weather.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } }
Why Uri.https? It builds and encodes the query parameters for you, so city names with spaces or special letters work correctly.

Step 5: Weather Code Helper

dart // lib/utils/weather_codes.dart import 'package:flutter/material.dart'; (String, IconData) describe(int code) { if (code == 0) return ('Clear sky', Icons.wb_sunny); if (code <= 3) return ('Partly cloudy', Icons.cloud_queue); if (code == 45 || code == 48) return ('Fog', Icons.foggy); if (code >= 51 && code <= 67) return ('Rain', Icons.grain); if (code >= 71 && code <= 77) return ('Snow', Icons.ac_unit); if (code >= 80 && code <= 82) return ('Showers', Icons.water_drop); if (code >= 95) return ('Thunderstorm', Icons.thunderstorm); return ('Unknown', Icons.help_outline); }

Step 6: The Screen

dart // lib/main.dart import 'package:flutter/material.dart'; import 'models/weather.dart'; import 'services/weather_service.dart'; import 'utils/weather_codes.dart'; void main() => runApp(const WeatherApp()); class WeatherApp extends StatelessWidget { const WeatherApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Weather', debugShowCheckedModeBanner: false, theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.lightBlue)), home: const WeatherPage(), ); } } class WeatherPage extends StatefulWidget { const WeatherPage({super.key}); @override State<WeatherPage> createState() => _WeatherPageState(); } class _WeatherPageState extends State<WeatherPage> { final _service = WeatherService(); final _controller = TextEditingController(text: 'Pune'); Future<(City, Weather)>? _future; @override void initState() { super.initState(); _search(); } @override void dispose() { _controller.dispose(); super.dispose(); } void _search() { final name = _controller.text.trim(); if (name.isEmpty) return; FocusScope.of(context).unfocus(); setState(() { _future = _load(name); }); } Future<(City, Weather)> _load(String name) async { final city = await _service.findCity(name); final weather = await _service.getWeather(city); return (city, weather); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Weather')), body: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ TextField( controller: _controller, textInputAction: TextInputAction.search, onSubmitted: (_) => _search(), decoration: InputDecoration( hintText: 'Search city', border: const OutlineInputBorder(), suffixIcon: IconButton(icon: const Icon(Icons.search), onPressed: _search), ), ), const SizedBox(height: 16), Expanded( child: FutureBuilder<(City, Weather)>( future: _future, builder: (context, snapshot) { if (_future == null) return const SizedBox(); if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center( child: Text( '${snapshot.error}'.replaceFirst('Exception: ', ''), textAlign: TextAlign.center, ), ); } final (city, weather) = snapshot.data!; return WeatherView(city: city, weather: weather); }, ), ), ], ), ), ); } } class WeatherView extends StatelessWidget { final City city; final Weather weather; const WeatherView({super.key, required this.city, required this.weather}); static const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; @override Widget build(BuildContext context) { final (text, icon) = describe(weather.code); final scheme = Theme.of(context).colorScheme; return ListView( children: [ Card( color: scheme.primaryContainer, child: Padding( padding: const EdgeInsets.all(24), child: Column( children: [ Text('${city.name}, ${city.country}', style: Theme.of(context).textTheme.titleLarge), const SizedBox(height: 8), Icon(icon, size: 72), Text('${weather.temperature.round()}°C', style: Theme.of(context).textTheme.displayMedium), Text(text), const SizedBox(height: 8), Text('Wind ${weather.windSpeed.round()} km/h'), ], ), ), ), const SizedBox(height: 16), Text('Forecast', style: Theme.of(context).textTheme.titleMedium), for (final d in weather.days.take(5)) ListTile( leading: Icon(describe(d.code).$2), title: Text(_weekdays[d.date.weekday - 1]), trailing: Text('${d.max.round()}° / ${d.min.round()}°'), ), ], ); } }

What You Practiced

  • Two chained API calls (city, then weather)
  • Typed models with safe number conversion
  • Dart 3 records, (City, Weather), as a return type
  • Complete loading, error and data states

Challenges

  • Remember the last city with shared_preferences
  • Use the geolocator package to get the weather at your current location
  • Add an hourly forecast chart with fl_chart
  • Switch between Celsius and Fahrenheit

Conclusion

You connected an app to a live API, parsed real JSON and built a clean UI. This pattern works for almost any API-driven app.

Quick Summary: Search a city with the geocoding API, fetch the forecast, parse into models, and show loading, error and data states.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators