Flutter Course: Finishing the Weather App: 15.11

In this course, we will go through the final stages of completing a weather app using Flutter. In this section, we will cover several important elements such as optimizing the app’s user interface (UI), data handling, and API integration. All of these processes are aimed at providing a better experience for the user.

Project Environment Setup

First, ensure that the project is properly set up. Make sure you have installed the Flutter SDK along with Android Studio or Visual Studio Code. Also, to ensure that the Flutter environment is correctly configured, run the following command in the terminal:

flutter doctor

This command will check all configured environments and notify you if there are any additional setups required.

Integrating the API

The core of the weather application is the data source. We will use the OpenWeatherMap API to fetch real-time weather data. To get an API key, sign up on the OpenWeatherMap website and obtain your key.

We will use the HTTP library to call the API. Use the following command to add the HTTP library:

flutter pub add http

Next, let’s implement a function to send HTTP requests:

import 'package:http/http.dart' as http;

Future fetchWeatherData(String city) async {
    final apiKey = 'YOUR_API_KEY';
    final url = 'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric';
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
        // Data processing logic
    } else {
        throw Exception('Failed to load weather data');
    }
}

Data Modeling

To model the weather data, we need to create a model class that can map the JSON data to the class. For example:

class Weather {
    final String cityName;
    final double temperature;
    final String description;

    Weather({required this.cityName, required this.temperature, required this.description});

    factory Weather.fromJson(Map json) {
        return Weather(
            cityName: json['name'],
            temperature: json['main']['temp'],
            description: json['weather'][0]['description'],
        );
    }
}

State Management

In Flutter, there are various ways to manage state. In this example, we will use the Provider pattern. We will add the Provider package and implement the WeatherProvider class:

import 'package:flutter/material.dart';

class WeatherProvider with ChangeNotifier {
    Weather? _weather;

    Weather? get weather => _weather;

    Future getWeather(String city) async {
        // API call and data fetching
        final data = await fetchWeatherData(city);
        _weather = Weather.fromJson(data);
        notifyListeners();
    }
}

Building the UI

Now let’s implement the most important and interesting part, the UI. Using Flutter widgets, we will create a simple yet intuitive user interface. The basic structure is as follows:

Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('Weather App'),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    Text('City Name: ${weatherProvider.weather?.cityName}'),
                    Text('Temperature: ${weatherProvider.weather?.temperature}°C'),
                    Text('Condition: ${weatherProvider.weather?.description}'),
                ],
            ),
        ),
    );
}

Updating State

The UI needs to be updated whenever the state changes. To do this, use the Consumer widget from Provider to detect state changes and rebuild the UI:

Consumer(
    builder: (context, weatherProvider, child) {
        if (weatherProvider.weather != null) {
            return WeatherDisplay(weather: weatherProvider.weather!);
        } else {
            return CircularProgressIndicator(); // Loading data
        }
    },
)

Final Steps and Build

Once all the code is written, it’s time to run the app and check the results. Enter the following command in the terminal to run the app:

flutter run

With that, a simple weather application using Flutter has been completed. Additionally, you can add various features to improve the user experience. For example, adding search functionality and location-based services can make it more convenient for users to check weather information.

Conclusion

Through this course, you learned the fundamental process of building a weather app using Flutter, including user interfaces, API usage, and state management. Try to continuously develop the app by adding and improving various features. Thank you.