DeveloperBreeze

Prerequisites

Before we start, ensure that your Flutter environment is set up. You should have Flutter and Dart installed, along with an IDE like Android Studio or Visual Studio Code.

Overview

Our weather app will:

  • Fetch weather data from an external API.
  • Display current temperature, weather conditions, and an icon representing the weather.
  • Implement navigation between different screens.

Step 1: Setting Up the Project

Create a new Flutter project:

flutter create weather_app

Navigate to the project directory:

cd weather_app

Open the project in your preferred IDE.

Step 2: Add Dependencies

We’ll use the http package to make network requests and provider for state management. Update your pubspec.yaml file to include these dependencies:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
  provider: ^6.0.0

Run flutter pub get to install the packages.

Step 3: Create the UI

Let's start by building the UI components.

Create a WeatherScreen Widget

Create a new file lib/screens/weather_screen.dart and add the following code:

import 'package:flutter/material.dart';

class WeatherScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Weather App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'City Name',
              style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Text(
              '25°C',
              style: TextStyle(fontSize: 56),
            ),
            SizedBox(height: 16),
            Icon(
              Icons.wb_sunny,
              size: 100,
            ),
            SizedBox(height: 16),
            Text(
              'Clear Sky',
              style: TextStyle(fontSize: 24),
            ),
          ],
        ),
      ),
    );
  }
}

Update main.dart

Modify lib/main.dart to load WeatherScreen:

import 'package:flutter/material.dart';
import 'screens/weather_screen.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Weather App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherScreen(),
    );
  }
}

Step 4: Integrate Weather API

We will use the OpenWeatherMap API to fetch weather data. You’ll need to sign up and get an API key.

Create a Weather Model

Create a new file lib/models/weather.dart and define the data model:

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

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

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

Fetch Weather Data

Create a new file lib/services/weather_service.dart to handle API requests:

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/weather.dart';

class WeatherService {
  final String apiKey = 'YOUR_API_KEY';
  final String baseUrl = 'https://api.openweathermap.org/data/2.5/weather';

  Future<Weather> fetchWeather(String city) async {
    final response = await http.get(Uri.parse('$baseUrl?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');
    }
  }
}

Step 5: Implement State Management

We will use the provider package to manage the app's state.

Create a Weather Provider

Create a new file lib/providers/weather_provider.dart:

import 'package:flutter/material.dart';
import '../models/weather.dart';
import '../services/weather_service.dart';

class WeatherProvider with ChangeNotifier {
  final WeatherService _weatherService = WeatherService();
  Weather? _weather;

  Weather? get weather => _weather;

  Future<void> fetchWeather(String city) async {
    _weather = await _weatherService.fetchWeather(city);
    notifyListeners();
  }
}

Update main.dart

Wrap the WeatherScreen with ChangeNotifierProvider:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'screens/weather_screen.dart';
import 'providers/weather_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => WeatherProvider(),
      child: MaterialApp(
        title: 'Flutter Weather App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: WeatherScreen(),
      ),
    );
  }
}

Step 6: Connect UI with State

Update the WeatherScreen to display real data.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/weather_provider.dart';

class WeatherScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final weatherProvider = Provider.of<WeatherProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Weather App'),
      ),
      body: Center(
        child: weatherProvider.weather == null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Enter City Name',
                    style: TextStyle(fontSize: 24),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: TextField(
                      onSubmitted: (value) {
                        weatherProvider.fetchWeather(value);
                      },
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'City',
                      ),
                    ),
                  ),
                ],
              )
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    weatherProvider.weather!.cityName,
                    style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 16),
                  Text(
                    '${weatherProvider.weather!.temperature}°C',
                    style: TextStyle(fontSize: 56),
                  ),
                  SizedBox(height: 16),
                  Image.network(
                    'http://openweathermap.org/img/wn/${weatherProvider.weather!.icon}@2x.png',
                  ),
                  SizedBox(height: 16),
                  Text(
                    weatherProvider.weather!.description,
                    style: TextStyle(fontSize: 24),
                  ),
                ],
              ),
      ),
    );
  }
}

Step 7: Testing the App

Run the app using:

flutter run

Test the app by entering different city names and observing the weather data displayed.

Conclusion

In this tutorial, we built a more advanced Flutter app that fetches real-time weather data using an API and displays it with a user-friendly interface. We covered:

  • Setting up an advanced UI with Flutter.
  • Integrating an external API to fetch real-time data.
  • Managing state with the provider package.

Next Steps

  • Add error handling for network requests.
  • Implement additional features like weather forecasts.
  • Explore other state management solutions like bloc or riverpod.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
dart

دليل شامل: تطوير تطبيقات باستخدام إطار العمل Flutter

flutter doctor
  • سيعرض هذا الأمر قائمة بالأدوات المطلوبة. أكمل تثبيت أي أدوات مفقودة.

Dec 12, 2024
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • JavaScript enables features like dropdown menus, modal windows, sliders, and real-time updates.
  • Examples: Search suggestions, form validations, chat applications.
  • Using AJAX or Fetch API, JavaScript retrieves and updates data without reloading the page.
  • Example: Infinite scrolling on social media feeds.

Dec 10, 2024
Read More
Tutorial
python

Build a Voice-Controlled AI Assistant with Python

   pip install requests
import requests

API_KEY = "your_openweathermap_api_key"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"

def get_weather(city):
    params = {"q": city, "appid": API_KEY, "units": "metric"}
    response = requests.get(BASE_URL, params=params)
    data = response.json()

    if data.get("cod") == 200:
        weather = data["weather"][0]["description"]
        temperature = data["main"]["temp"]
        speak(f"The weather in {city} is {weather} with a temperature of {temperature}°C.")
    else:
        speak("Sorry, I couldn't find the weather for that location.")

Dec 10, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

If the raw response is in the form of a query string (e.g., key1=value1&key2=value2), you can use PHP’s built-in parse_str() function to convert it into an associative array.

use Illuminate\Support\Facades\Http;

$response = Http::post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

$rawResponse = $response->body(); // Get the raw response
$parsedResponse = [];

// Parse the query string into an associative array
parse_str($rawResponse, $parsedResponse);

dd($parsedResponse); // Now you can work with the associative array

Oct 24, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POST Request with Fetch</title>
</head>
<body>
    <form id="postDataForm">
        <input type="text" id="title" placeholder="Enter title" required>
        <input type="text" id="body" placeholder="Enter body" required>
        <button type="submit">Submit</button>
    </form>
    <div id="postDataOutput"></div>

    <script>
        document.getElementById('postDataForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const title = document.getElementById('title').value;
            const body = document.getElementById('body').value;

            fetch('https://jsonplaceholder.typicode.com/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: title,
                    body: body
                })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('postDataOutput').innerHTML = `
                    <h3>Data Submitted:</h3>
                    <p>Title: ${data.title}</p>
                    <p>Body: ${data.body}</p>
                `;
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>
  • The form is submitted without a page reload by preventing the default form submission behavior.
  • We send a POST request to the API using fetch(), including the form data as JSON in the request body.
  • The server's response is displayed on the page.

Sep 18, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Mobile App Development

This example demonstrates a simple app with a text message and a button. When the button is pressed, an alert message is displayed.

Navigation is an essential aspect of any mobile app. In React Native, the react-navigation library is commonly used to manage navigation between different screens.

Sep 02, 2024
Read More
Tutorial
javascript

Understanding Closures in JavaScript: A Comprehensive Guide

function greeting(message) {
    return function(name) {
        console.log(`${message}, ${name}!`);
    };
}

const sayHello = greeting("Hello");
sayHello("Alice");  // Output: "Hello, Alice!"
sayHello("Bob");    // Output: "Hello, Bob!"

const sayGoodbye = greeting("Goodbye");
sayGoodbye("Alice");  // Output: "Goodbye, Alice!"

Here, the greeting function creates a closure that remembers the message variable. This allows the inner function to use message whenever it is called.

Aug 30, 2024
Read More
Tutorial
javascript php

Building a Custom E-commerce Platform with Laravel and Vue.js

Here’s what each directory and file will be used for:

  • components/: This directory contains reusable Vue components such as ProductList.vue and ProductDetail.vue.
  • store/: This directory will contain the Vuex store, which manages the state of your application.
  • views/: This directory contains the main pages or views of your application, such as the Home and Product pages.

Aug 27, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Tutorial
php

Integrating and Using NMI Payment Gateway in Laravel

Add the following method to the NMI class:

   public function processPaymentUsingVault($customerVaultId, $totalAmount)
   {
       $data = [
           'security_key' => $this->securityKey,
           'customer_vault_id' => $customerVaultId,
           'amount' => $totalAmount,
       ];

       if ($this->production === false) {
           $data['test_mode'] = 'enabled';
       }

       $curl = curl_init();
       curl_setopt_array($curl, [
           CURLOPT_URL => $this->url,
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_POST => true,
           CURLOPT_POSTFIELDS => http_build_query($data),
           CURLOPT_SSL_VERIFYHOST => false,
           CURLOPT_SSL_VERIFYPEER => false,
       ]);
       $response = curl_exec($curl);
       curl_close($curl);

       if ($response === false) {
           return [
               'responsetext' => 'error',
               'error' => 'Payment processing failed',
           ];
       }

       \Log::info('NMI Payment Response: ' . $response);

       parse_str($response, $parsedResponse);

       return $parsedResponse;
   }

Aug 14, 2024
Read More
Tutorial
dart

Introduction to Flutter and Dart

Open a terminal and run the following command:

flutter create my_flutter_app

Aug 12, 2024
Read More
Code
javascript

Weather App with Node.js

Create a new directory for your project and navigate into it:

mkdir weather-app
cd weather-app

Aug 08, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

In the src/index.js file, wrap your <App /> component with the <Provider> component from react-redux, passing it the store as a prop.

   import React from 'react';
   import ReactDOM from 'react-dom/client';
   import { Provider } from 'react-redux';
   import store from './store';
   import App from './App';
   import './index.css';

   const root = ReactDOM.createRoot(document.getElementById('root'));
   root.render(
     <Provider store={store}>
       <App />
     </Provider>
   );

Aug 05, 2024
Read More
Code
javascript

POST Request with Fetch API and JSON Data

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!