Building a Weather App in Flutter Using REST APIs
Durga jayasai Pillagolla
Building WorkWave || Student at KL University || Student Peer Mentor || Advisor at Kognitiv club
Introduction
In the world of mobile application development, real-time data fetching from the internet is critical for building dynamic and engaging user experiences. One frequent use case is creating a weather app that offers customers current weather information. In this article, we'll look at how to build a simple weather app in Flutter utilizing a REST API.
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a set of principles that enable various software programs to communicate via the internet. It enables developers to communicate with online services via normal HTTP methods such as GET, POST, PUT, and DELETE.
Why Use a Weather API?
Weather APIs enable access to current and expected weather data from a variety of locations across the world. Using these APIs, you may improve your applications with real-time weather data, increasing user engagement and effectiveness.
Step-by-Step Guide to Creating a Weather App
1. Choose a Weather API
For this example, we’ll use the OpenWeatherMap API. First, sign up for an account and get your API key: OpenWeatherMap API
2. Set Up Your Flutter Project
Create a new Flutter project with the following commands in your terminal:
flutter create weather_app
cd weather_app
3. Add Dependencies
To make HTTP requests and manage environment variables securely, add the following dependencies to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
http: ^1.2.2
flutter_dotenv: ^5.1.0
Run flutter pub get to install the packages.
4. Create a .env file
In your root project, create a .env file to store your OpenWeatherMap API key:
API_KEY=your_api_key_here
5. Load Environment Variables
In your main.dart file, load the environment variables like this:
领英推荐
void main() async {
await dotenv.load(fileName: ".env");
runApp(MyApp());
}
6. Fetch Weather Data
Create a service class to fetch weather data from the API:
class WeatherService {
Future<Map<String, dynamic>> fetchWeather(String city) async {
final apiKey = dotenv.env['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 json.decode(response.body);
} else {
throw Exception('Failed to load weather data');
}
}
}
7. Build the User Interface
Create a simple UI to input the city name and display the weather data:
class WeatherHomePage extends StatefulWidget {
@override
_WeatherHomePageState createState() => _WeatherHomePageState();
}
class _WeatherHomePageState extends State<WeatherHomePage> {
final TextEditingController _controller = TextEditingController();
Map<String, dynamic>? _weatherData;
final WeatherService _weatherService = WeatherService();
void _getWeather() async {
String city = _controller.text;
try {
final data = await _weatherService.fetchWeather(city);
setState(() {
_weatherData = data;
});
} catch (e) {
print(e);
setState(() {
_weatherData = null;
});
}
}
@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',
suffixIcon: IconButton(
icon: Icon(Icons.search),
onPressed: _getWeather,
),
),
),
SizedBox(height: 20),
_weatherData != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Weather in ${_weatherData!['name']}',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
Text('Temperature: ${_weatherData!['main']['temp']}°C'),
Text('Weather: ${_weatherData!['weather'][0]['description']}'),
],
)
: Text('No data available'),
],
),
),
);
}
}
8. Running the App
Run the app using the command:
flutter run
Output
Note
If you want to include animations for different weather situations (such as sunny, overcast, rainy, and so on) in your Flutter weather app, modify or design it according to your needs.
Conclusion
Building a weather app in Flutter with REST APIs is a pleasant experience that demonstrates the value of real-time data integration. By following these steps, you may construct a basic weather application that retrieves and displays weather data based on user input.
Next Steps
This project not only helps to solidify your understanding of REST APIs in Flutter, but it also acts as a foundation for more advanced apps. Happy coding! ???
Please let me know if you need any tweaks!