In today’s lecture, we will discuss how to fetch real-time weather data using Flutter. Weather applications are one of the projects that many developers create as their first project, providing an interesting experience of easily fetching weather data via an API and displaying it in the UI. In this lecture, we will learn about various topics such as API calls, JSON data parsing, and utilizing StatefulWidget.
Minimum Requirements
- You should have Flutter SDK and development environment installed.
- A basic understanding of the Dart language and Flutter framework is required.
- We will use Pub.dev to utilize external libraries.
1. Project Setup
To create a new Flutter project, execute the following command:
flutter create weather_app
After navigating into the created project folder, open the lib/main.dart
file.
2. Installing Required Packages
We will use the HTTP package to fetch weather data. Add the following dependency to the pubspec.yaml
file:
dependencies:
http: ^0.13.3
After saving the changes, install the package with the following command:
flutter pub get
3. Selecting API and Obtaining Key
In this lecture, we will use the OpenWeatherMap API to fetch real-time weather data. Follow these steps to use the API.
- Go to the OpenWeatherMap website and create an account.
- Generate an API key and make a note of it.
4. Creating Weather Data Model
It is necessary to understand the structure of the weather data returned by the API and convert it to a Dart model. Here is a simple model to represent weather data:
class Weather {
final String description;
final double temperature;
Weather({required this.description, required this.temperature});
factory Weather.fromJson(Map json) {
return Weather(
description: json['weather'][0]['description'],
temperature: json['main']['temp'],
);
}
}
5. Fetching Data: HTTP GET Request
Now, let’s create an HTTP GET request to fetch weather data from the API. Add the following function to the main file:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future fetchWeather(String city) async {
final String apiKey = 'YOUR_API_KEY'; // Change to your API key
final response = await http.get(Uri.parse('https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric'));
if (response.statusCode == 200) {
return Weather.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load weather data');
}
}
6. Building the UI
Now, let’s create the user interface. Build a simple UI that takes user input for the city name and displays weather information:
import 'package:flutter/material.dart';
void main() {
runApp(WeatherApp());
}
class WeatherApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Weather App',
home: WeatherHomePage(),
);
}
}
class WeatherHomePage extends StatefulWidget {
@override
_WeatherHomePageState createState() => _WeatherHomePageState();
}
class _WeatherHomePageState extends State {
final TextEditingController _controller = TextEditingController();
Weather? _weather;
String? _errorMessage;
void _getWeather() async {
try {
final weather = await fetchWeather(_controller.text);
setState(() {
_weather = weather;
_errorMessage = null;
});
} catch (e) {
setState(() {
_errorMessage = e.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Weather App'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Enter city name'),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _getWeather,
child: Text('Get Weather'),
),
SizedBox(height: 20),
if (_errorMessage != null)
Text(
_errorMessage!,
style: TextStyle(color: Colors.red),
),
if (_weather != null) ...[
Text('Temperature: ${_weather!.temperature}°C'),
Text('Description: ${_weather!.description}'),
],
],
),
),
);
}
}
7. Running the App
Once all the code is written, run the app to check if it works. You can start the app using the following command in the terminal:
flutter run
Enter the city name and click the ‘Get Weather’ button to display the real-time weather information for that city.
8. Future Improvements
This application provides only basic weather information. Consider the following improvements:
- Add GPS functionality to get weather for the current location
- Display more weather information (humidity, pressure, etc.)
- Enhance the UI for a better user experience
- Support offline mode
Conclusion
In this lecture, we created a simple application to fetch real-time weather data using Flutter. We learned how to use the weather API and how to obtain data from it. We hope you lay the foundation to progress to more complex applications.
If you have any questions or comments, feel free to leave them in the comments!