In this section, we will learn how to integrate the OpenWeatherMap API into a Flutter application. OpenWeatherMap provides various useful weather information, including real-time weather data, temperature, humidity, and wind speed. This API offers both free and paid plans, and today we will explain based on the free plan.
1. Sign up for OpenWeatherMap API and get the API key
The first step is to sign up on the OpenWeatherMap website to obtain an API key. Please follow the steps below:
- Go to the OpenWeatherMap website.
- Click “Sign Up” in the top menu to create an account.
- Enter your email address and password, then complete the registration process.
- After logging in, navigate to the “API keys” menu to check your automatically generated default API key.
- You can create a new API key if needed.
2. Setting up the Flutter project
Now let’s set up the Flutter project. You can either create a new Flutter application or use an existing project.
flutter create weather_app
Navigate to the project directory:
cd weather_app
Next, add the required package to the pubspec.yaml file to send HTTP requests:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
Run the following command to install all dependencies:
flutter pub get
3. Creating the weather data model
Create a Dart model class to learn the JSON data received from the OpenWeatherMap API. For example, let’s create a class for weather data.
class Weather {
final String city;
final double temperature;
final String description;
Weather({required this.city, required this.temperature, required this.description});
factory Weather.fromJson(Map json) {
return Weather(
city: json['name'],
temperature: json['main']['temp'] - 273.15, // Convert Kelvin to Celsius
description: json['weather'][0]['description'],
);
}
}
4. Fetching weather data with HTTP requests
Now it’s time to write the HTTP request to fetch weather information. We will send a GET request to the OpenWeatherMap API using the http package.
Here’s an example of writing a function to fetch weather information:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future fetchWeather(String city) async {
final apiKey = 'YOUR_API_KEY_HERE'; // Enter your API key here
final response = await http.get(Uri.parse('https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey'));
if (response.statusCode == 200) {
return Weather.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load weather data');
}
}
5. Creating the user interface
Now let’s create a simple user interface to display the weather information. We will use Flutter components to show weather information based on the city name entered by the user.
Here’s a basic UI code example:
import 'package:flutter/material.dart';
class WeatherApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Weather App',
home: Scaffold(
appBar: AppBar(
title: Text('Weather Information'),
),
body: WeatherInfo(),
),
);
}
}
class WeatherInfo extends StatefulWidget {
@override
_WeatherInfoState createState() => _WeatherInfoState();
}
class _WeatherInfoState extends State {
String city = '';
Weather? weather;
final TextEditingController controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: controller,
decoration: InputDecoration(labelText: 'Enter City Name'),
),
),
ElevatedButton(
onPressed: () {
setState(() {
city = controller.text.trim();
});
fetchWeather(city).then((value) {
setState(() {
weather = value;
});
}).catchError((error) {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Error'),
content: Text(error.toString()),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
),
);
});
},
child: Text('Get Weather'),
),
if (weather != null)
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'City: ${weather!.city}\nTemperature: ${weather!.temperature.toStringAsFixed(1)}°C\nCondition: ${weather!.description}',
style: TextStyle(fontSize: 20),
),
),
],
);
}
}
void main() {
runApp(WeatherApp());
}
6. Run the app and check the results
You can run the code written above on a device or emulator to check the results. Now, when you enter a city name in the input field and press the “Get Weather” button, it will display the weather information fetched through the API request on the screen.
7. Error handling and improvements
The currently implemented example provides only basic functionality, so there are various improvements that can be added. For example:
- Location-based weather information provision: Add a feature to automatically fetch weather information based on the user’s current location.
- Caching weather information: Add a caching mechanism to reduce response time for the same requests.
- Improving colors and design: Refine the UI design to enhance user experience.
- Providing various weather information: Display additional information such as humidity, wind speed, etc., besides temperature.
8. Conclusion
In this post, we have detailed how to fetch real-time weather information using Flutter and the OpenWeatherMap API. I hope this helps you learn how to use the API and add various features through practice. In the future, I encourage you to create many innovative applications using Flutter!